Home > Blockchain >  In TypeScript, how do I assert the value of a class variable using a method?
In TypeScript, how do I assert the value of a class variable using a method?

Time:11-01

I want a method that will tell typescript my client was initialised (is no longer null). Basically, I'm able to do this but in a way that seems needlessly verbose. Here's my current implementation:

export abstract class CacheService {
    storeClient: ICacheStoreInterface | null = null

    protected constructor(storeClientGetter: () => Promise<ICacheStoreInterface>) {
        this.logger = Container.get(Logger)
        void this.initialise(storeClientGetter)
    }

    private checkInitialisation(client: ICacheStoreInterface | null): asserts client is ICacheStoreInterface {
        if (!this.storeClient) {
            throw new Error('Attempting to access cache before initialisation')
        }
    }

    private async initialise(storeClientGetter: () => Promise<ICacheStoreInterface>) {
        try {
            this.storeClient = await storeClientGetter()
        } catch (error) {
            this.logger.error(`Error initialising cache service:\n${error}`)
        }
    }

    public async set(key: storeKey, value: any) {
        this.checkInitialisation(this.storeClient)
        await this.storeClient.set(key, value)
    }

    public async get(key: storeKey) {
        this.checkInitialisation(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

TS playground link

What I want to do is achieve the same result BUT without having to explicitly pass this.storeClient to the checkInitialisation method. It seems like it might be possible as both the method and the parent function have access to the variable so maybe they can share type data somehow? In essence, I'm looking for something like asserts this.storeClient is ICacheStoreInterface though that exact example won't work. Is this possible or am I going to have to live with the minor inconvenience of this "pointless" variable?

CodePudding user response:

There's no direct support for type predicates of the form arg.prop is Type, nor for assertion predicates of the form asserts arg.prop is Type. See microsoft/TypeScript#11117 for an open feature request for such functionality, at least for type predicates. It's listed as "awaiting more feedback" so you might want to go there, give it a

  • Related