Reputation: 15690
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
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