Search code examples
ooptypescriptgenericsnested-generics

Extending a generics class with nested generics


is there a way in typescript to extend a class in this way:

class ChildClass<Wrapper<A>> extends SuperClass<A>

This doesn't work but the idea would be to wrap the generics type into a known construct. Here are the docs:

https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md

This sounds a bit similar to this issue:

Can you subclass a generics class with a specific typed class?

I don't do much oop so I'm not very familiar with stuff like covariance and contravariance, any help would be appreciated.


Solution

  • It maeks no sense to write ChildClass<Wrapper<A>> before the extends, because there you declare the generic type parameters. That means you can give them a name and, if you need to, a constraint (for example ChildClass<A extends Wrapper>). What does Wrapper<A> mean in this context? The compiler can make no sense of it.

    What is absolutely possible is to use Wrapper<A> on the other side of the extends, because there A is not a (formal) type parameter, but a type argument. That means you are using the type parameter previously defined and there you can generate new types with it.

    So depending on what you actually want to do, there are two options for you:

    A is assignable to Wrapper

    When you want to make sure the A is a Wrapper or a derived class, use a generic constraint:

    class ChildClass<A extends Wrapper> extends SuperClass<A>
    

    A is a type argument of Wrapper<>

    If Wrapper<> is itself a generic class or interface and you want to use A as its type argument, do this:

    class ChildClass<A> extends SuperClass<Wrapper<A>>