Home > Back-end >  TypeScript is there some elegant way to reflect child class type in the parent class?
TypeScript is there some elegant way to reflect child class type in the parent class?

Time:07-16

I has a base class

class Animal {
  public abstract clone(): Animal
}

and some derived classes

class Dog extends Aniaml {
  public clone(): Dog {
    return clone(this)
  }
}
class Cat extends Aniaml {
  public clone(): Cat {
    return clone(this)
  }
}

Since the clone() implementations in the derived classes is identical each other. DRY priciple tells me that the code is less elegent.

So the version 2:

class Animal {
  public clone(): Animal {
    return clone(this)
  }
}
class Dog extends Aniaml {}
class Cat extends Aniaml {}

In this way, it's more elegant. But there is one thing bother me which, see below:

const dog = new Dog()
const clonedDog = dog.clone() // typeof clonedDog is 'Animal'
const clonedDog = dog.clone() as Animal // typeof clonedDog is 'Dog' but I dont want type assertion here

So, the question is: Is there the elegant way to auto infer clone() 's concrete return type in the derived classes?

I already had one solution but I dont think it's elegant :(

// still less elegant
class Animal<T> {
  public clone(): <T> {
    return clone(this)
  }
}
class Dog extends Aniaml<Dog> {}
class Cat extends Aniaml<Cat> {}

THANKS for the any help!!!

CodePudding user response:

Use the this type. It is the type of the current implementation.

class Animal {
    clone(): this {
        return clone(this)
    }
}

class Dog extends Animal {}

const dog = new Dog()
const clonedDog = dog.clone() // Dog
  • Related