In a scenario where I have a class ShopManager
with a property _itemCategories
whose value is going to be set to the return value of an asynchronous function, since I couldn't use async/await
inside the class' constructor, I declared an init
async function which would be called from the outside and would set its value.
However, the initial value of _itemCategories
, before init
is called, would be either null
or undefined
. This makes me have to check if an instance of ShopManager
's itemCategories
is present every single time I use it anywhere on my application, which isn't ideal.
import type { Application } from '../application';
export class ShopManager {
private readonly _application: Application;
private _itemCategories: string[] | null = null;
public get itemCategories() {
return this._itemCategories;
}
public constructor(application: Application) {
this._application = application;
}
public async init() {
this._itemCategories = await this._getItemCategories();
}
private async _getItemCategories(): Promise<string[]> {
const categories = await this._application.storage.itemCategory.findMany();
return categories.map((category) => category.name);
}
}
I'm wondering if there's a better way to set properties of classes based on the return of asynchronous functions, or if I can somehow make TypeScript infer that itemCategories
is present after calling init
(extremely unlikely I believe).