In my coding journey, I came across a situation where I was dealing with generic classes. Specifically, I had a Generic class Generic<T>
and another one called GenericWrap that used Generic as its maximum type parameter (denoted as U extends Generic<any>
). Inside GenericWrap, there is a member named generic, which is an instance of Generic using any as the value type.
In an attempt to extend the functionality further, I created NumberGenericWrap by extending GenericWrap with a type parameter <NumberGeneric>
. My goal was to set the type of NumberGenericWrap.generic
to be Generic<number>
, allowing the result of NumberGenericWrap.getValue()
to be of type number
. However, when testing it out, I noticed that the return type ended up being 'any' instead.
This made me wonder - does TypeScript actually support what I am trying to achieve here?
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();