How to allow class method overwrite with Typescript?

Viewed 167

I have a class Animal with some methods, and an extension of the class - called Bird - that overwrites one of its parent methods to handle an edgecase.

It looks like this:

class Animal {
  constructor(animal) {
    this.animal = animal;
  }
  public define(){
    return {name: this.animal.name}
  }
}

class Bird extends Animal{
  public define(){
    return {color: this.animal.color}
  }
}

Calling bird.define() works fine. But Typescript goes mad, claiming:

Property 'define' in type 'Bird' is not assignable to the same property in base type 'Animal'. Type '() => { color: string; }' is not assignable to type '() => { name: string }'. Type '{ color: string; }' is missing the following properties from type '{ name: string; }':
name

How to fix this except doing a ts-ignore?

1 Answers

Here you have a workaround:


type AnimalObj = {
    name: string;
    color: string
}
class Animal {
    constructor(public animal: AnimalObj) {
        this.animal = animal;
    }
    public define(): Partial<AnimalObj> {
        return { name: this.animal.name }
    }
}

class Bird extends Animal {
    public define() {
        return { color: this.animal.color }
    }
}

There is no need to use ts-ignore in this particular case

Related