I need a more concise method to inform TypeScript that my client has been initialized (no longer null). While I have achieved this functionality, the current implementation seems unnecessarily verbose. Here is how it currently looks:
export abstract class CacheService {
storeClient: ICacheStoreInterface | null = null
protected constructor(storeClientGetter: () => Promise<ICacheStoreInterface>) {
this.logger = Container.get(Logger)
void this.initialize(storeClientGetter)
}
private checkInitialization(client: ICacheStoreInterface | null): asserts client is ICacheStoreInterface {
if (!this.storeClient) {
throw new Error('Attempting to access cache before initialization')
}
}
private async initialize(storeClientGetter: () => Promise<ICacheStoreInterface>) {
try {
this.storeClient = await storeClientGetter()
} catch (error) {
this.logger.error(`Error initializing cache service:\n${error}`)
}
}
public async set(key: storeKey, value: any) {
this.checkInitialization(this.storeClient)
await this.storeClient.set(key, value)
}
public async get(key: storeKey) {
this.checkInitialization(this.storeClient)
return this.storeClient.get(key)
}
}
export interface ICacheStoreInterface {
get(key: storeKey): Promise<any>
set(key: storeKey, value: any): Promise<void>
}
export type storeKey = number | string | symbol
The goal is to achieve the same outcome without explicitly passing this.storeClient to the checkInitialization method. It seems feasible since both the method and the parent function have access to the variable. Is there a way for them to share type data automatically? Essentially, I am seeking something like
asserts this.storeClient is ICacheStoreInterface
, although that exact example may not work. Is it possible, or will I need to accept the minor inconvenience of this seemingly "pointless" variable?