Use type of inheriting class in superclass

40 views Asked by At

Consider the following code...:

class Car {
    public static createInstance():Car {
        return new this();
    }
}

class Ferrari extends Car {
    fast:boolean = true;
}

class AutoCycle extends Car {
    slow:boolean = true;
}

let myCar:Ferrari = Ferrari.createInstance();

...This will give me the error Type 'Car' is not assignable to type 'Ferrari' with the following explanation: Property 'fast' is missing in type 'Car'

Of course I could prevent this error by skipping the type after let myCar or omit the return type of createInstance. Another option would be to do a type cast at the assignment.

But where's the fun in using TypeScript, if I must refrain from using types properly? ;-)

Hence my question: Is there a way to do something like

public static createInstance():this { //...

(Where this is to be internally auto-replaced by Ferrari in my example)?

0

There are 0 answers