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?
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; };
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.
You can call the base class constructor from the child class by using the super() which will execute the constructor of the base class.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With