'Call function from superclass with different this
I have Owner class, Animal (which might have an owner), Dog (which extends Animal) and a type WithOwner which makes sure that animal has an owner:
type WithOwner<T extends Animal> = T & {
owner: NonNullable<T["owner"]>;
};
class Owner {
name: string;
constructor(name: string) {
this.name = name;
}
}
class Animal {
owner?: Owner;
ownership(this: WithOwner<Animal>): string {
return this.owner.name;
}
}
class Dog extends Animal {
override ownership(this: WithOwner<Dog>): string {
return super.ownership() + " owns a dog";
}
}
However I get an error on super.ownership(): TS2684: The 'this' context of type 'Animal' is not assignable to method's 'this' of type 'WithOwner<Animal>'.. For some reason TS compiler forgets that inside this function animal has an owner.
Any ideas what's going on here and how to fix it? I tried adding if (this.owner) before super but it still didn't help.
Solution 1:[1]
Be aware that JavaScript (and typescript) this is implicit supplied to a function, if you want a parameter, don't call it this.
also this
Solution 2:[2]
Figured it out. This works:
class Dog extends Animal {
override ownership(this: WithOwner<Dog>): string {
return super.ownership.call(this) + " owns a dog";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | K0IN |
| Solution 2 |
