AweSIM AweSIM - 16 days ago 5
TypeScript Question

Typescript :: namespacing functions within a class?

Assume a simple class like so:

class Simple {
private _transactions: [];
makeTransaction() { ... }
revertTransaction() { ... }
// some other methods as well...
}

let obj = new Simple();
obj.makeTransaction(...);
obj.makeTransaction(...);
obj.revertTransaction(...);


Now, I want to expose some more methods related to reporting and I would like to group them like so:

obj.reports.allTransactions();
obj.reports.reveretedTransactions();
obj.reports.clearedTransactions();


These methods will be using the private variables within the
Simple
class itself to return some reports.

I have used the following to achieve this:

class Simple {
private _test = () => { return this._transaction }
reports = {
getAll: this._test
}
}


This works, but it has a couple of downsides:


  1. It forces me to declare all required functions as part of the class itself and then reference them in the
    reports
    object again.

  2. Typescript shows me that
    obj.reports.getAll
    is a property, although I can invoke it as a function too. Even so, I don't get the correct function signature hint.

  3. It forces me to use arrow functions (closures) needlessly.



Is there a better way of doing the same?

Answer

You can create a class for the reports object:

class Reports {
    private _transactions: any[];

    constructor(transactions: any[]) {
        this._transactions = transactions;
    }

    getAll() {
        return this._transactions;
    }
}

class Simple {
    private _transactions: any[];
    public reports: Reports;

    constructor() {
        this._transactions = [];
        this.reports = new Reports(this._transactions);
    }

    makeTransaction() {}
    revertTransaction() { }
}

(code in playground)


Edit

You can also expose reports as a type:

interface Reports {
    getAll(): any[];
}

class Simple {
    private _transactions: any[];
    public reports: Reports;

    constructor() {
        this._transactions = [];
        this.reports = {
            getAll: () => {
                return this._transactions;
            }
        }
    }

    makeTransaction() {}
    revertTransaction() { }
}

(code in playground)