Ed Staub
Ed Staub

Reputation: 15690

How can I get this Typescript typeguard to work in a generic-type context?

The initialization of v2 below gives: Type 'T[keyof T]' cannot be converted to type 'number'. What is wrong?

private func<T extends Object>(o:T, prop: keyof(T)): void {
    const val = o[prop]
    if ( typeof val === 'number' ) {
        const v2: number = val as number
    }
}

This works in a non-generic context, below, [UPDATE] but this isn't useful as a workaround, since callers may only use properties of Object itself.

private func2(o:Object, prop: keyof(Object)): void {
    const val = o[prop]
    if ( typeof val === 'number' ) {
        const v2: number = val as number
    }
}

This is a silly example that I extracted to focus on the problem; if a real context would help, let me know.

Upvotes: 2

Views: 239

Answers (1)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37584

I am new to typescript, but I it seems like you have to double cast it as suggested here

  private func1<T extends Object>(o:T, prop: keyof(T)): void {
    const val = o[prop]
    if ( typeof val === 'number' ) {
        const v2: number = val as any as number
    }

Besides that you could use it like this maybe? I read it on the docs at least. Section Index Types

private func<T extends Object, K extends keyof T>(o: T, prop: K): void {
    const val = o[prop]
    if (typeof val === 'number') {
        const v2 = val as any as number
    }
}

Hope this helps.

Upvotes: 1

Related Questions