Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write this object access code more graceful?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading