Home > Net >  How to write this object access code more graceful?
How to write this object access code more graceful?

Time:10-25

I have some problems in TypeScript object access. For example, I have code like this:

enum DataTypes {...}
class Cache {
    private _data: Partial<Record<DataTypes, Data>> = {};
    private getExpensiveData(name: DataTypes): Data {...}
    private get(name: DataTypes) {
        if(!(name in this._data)) {
            this._data[name] = this.getExpensiveData(name)
        }
        return this._data[name] //return type Data | undefined
    }
}

For now i can only write the last line of get as return this._data[name] as Data, but is there a way to write it more beautifully?

Sorry i didn't say it clearly, but i actually mean is there are way make TS can infer it not null, not more simple ways to as it.

CodePudding user response:

You can use the null-coalescing operator as an augmented assignment:

return this._data[name] ??= this.getExpensiveData(name);

Since the ?? operator is short-circuiting, the right-hand side will only be evaluated if the left-hand side is undefined (or null).

Playground Link

  • Related