Obiwahn
Obiwahn

Reputation: 3087

Typescript sub classes: refer to derived class in super class?

class A {
    parentList: List<A>;
}

class B extends A {}

Is there any way that parentList is automatically of type List<B> for class B (without redefining for every subclass)?

Upvotes: 1

Views: 242

Answers (1)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10137

You need polymorphic this:

class A {
    public list: Array<this>;
}

class B extends A { }

declare const b: B;

const listOfB = b.list; // B[]

declare const a: A;

const listOfA = a.list; // A[]

Upvotes: 4

Related Questions