Reputation: 25
I have a generic class Generic<T>
and another generic class having another generic class as a generic type which is GenericWrap<U extends Generic<any>
. It has a Generic<any>
as a member. (Please see the code below)
Now NumberGenericWrap
extends GenericWrap
with a generic type <NumberGeneric>
. At this point, I want the type of NumerGenericWrap.generic
to be Generic<number>
so the return type of NumberGenericWrap.getValue()
can be number
. But it ends up with any
type.
Does typescript support this?
class Generic<T> {
val: T;
}
class NumberGeneric extends Generic<number> {
}
class GenericWrap<U extends Generic<any>> {
generic: U;
getValue() {
return this.generic.val;
}
}
class NumberGenericWrap extends GenericWrap<NumberGeneric> {
}
let n = new NumberGenericWrap();
// expected 'typeof val' => number
// actual 'typeof val' => any
let val = n.getValue();
Upvotes: 0
Views: 1623
Reputation: 481
I don't know exactly why is type checker not trying to infer val type, but it has workaround though. Just tell type checker to do the lookup to that generic type and find val type.
type ValType<T extends Generic<any>> = T["val"];
class GenericWrap<U extends Generic<any>> {
generic: U;
getValue(): ValType<U> {
return this.generic.val;
}
}
Upvotes: 1