Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript return type of inherited class

This is what I'm trying to do:

class Base{
    clone(){
        //return new instance of the inherited  class 
    }
}

class Derived extends Base{
}

const d1=new Derived();
const d2=d2.clone; // I want d2 to be of type Derived

What should be the the return type of the clone method for d2 to be of type Derived?

like image 273
ziv Avatar asked Feb 20 '17 12:02

ziv


People also ask

How do I return a class in TypeScript?

You need to export the class as well so that the consumer of the method can access the type. Typically a factory will return an instance rather than a class or constructor. export class Foo {}; export let factory = () => { return Foo; };

How do you get inheritance in TypeScript?

Inheritance in Typescript is a little different from Inheritance in Javascript. Javascript uses the function and prototype-based Inheritance, whereas Typescript uses class-based Inheritance. We can achieve Inheritance using the extends keyword in Typescript.

How do you call the base class constructor from the child class in TypeScript?

You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.

Which inheritance is supported in TypeScript?

Typescript uses class-based inheritance which is simply the syntactic sugar of prototypal inheritance. TypeScript supports only single inheritance and multilevel inheritance. In TypeScript, a class inherits another class using extends keyword.


1 Answers

I really hope there is a better way, but here is what I currently do:

class Base{
    clone(): this {
        return new (this.constructor as any)(); 
    }
}

class Derived extends Base {
}

class DerivedAgain extends Derived {

}

const d1=new Derived();
const d2 = d1.clone(); 
const d3 = new DerivedAgain().clone();

d2 is of type Derived, and d3 is of type DerivedAgain, as expected.

like image 147
Aviad Hadad Avatar answered Oct 15 '22 13:10

Aviad Hadad