2

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
  • 1
    This is intentional; a Bird is not an Animal if its define method returns something different. You will just have to rethink your software architecture a bit to determine what works best for you. Perhaps class hierarchies / extends are not needed here, and you can use some other form of JavaScript inheritance such as augmentation. Commented Mar 11, 2021 at 14:56

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.