I am facing some issues with TypeScript object access. Consider the following code snippet:
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
}
}
Currently, I am only able to write the last line of get
function as return this._data[name] as Data
. Is there a more elegant way to achieve this?
I apologize for not explaining clearly earlier, but what I'm trying to ask is if there's a method to make TypeScript infer it as not null without using as
.