Instantiating from this in TypeScript?

Viewed 355

I'm not sure this is possible, but this is what I'm trying to achieve...

abstract class Animal<T> {
  breed(mate: Animal<T>) {
    return new [this kind of animal]()
  }
}

class Cat extends Animal<Cat>{
  
}


let cat1 = new Cat();
let cat2 = new Cat();
let kitten = cat1.breed(cat2);

Is this type of thing possible, or would I need to create a breed method for every type of animal?

In ES6 JS you could use new this.constructor() but in Typescript this isn't possible:

abstract class Animal<T> {
  breed(mate: Animal<T>) {
    return new this.constructor()
  }
}

will give an error:

this expression is not constructable.
Type 'Function' has no construct signatures.
1 Answers

(property) Object.constructor: Function is Function, In typescript you cannot do new on top of it also this.constructor is not recognized as value of constructor type by TypeScript, but you can cast to any to get the new instance. In your case something similar to below -

abstract class Animal<T> {
  breed(mate: Animal<T>) {
    return new (<any>this.constructor);
  }
}

In JavaScript every function is considered as constructor when used with new hence the JavaScript code is working fine without any issues.

Related