I'm encountering an issue while trying to utilize TypeScript type checking with the following code snippet:
abstract class Mammal {
abstract breed(other: Mammal);
}
class Dog extends Mammal {
breed(other: Dog) {}
}
class Cat extends Mammal {
breed(other: Cat) {}
}
const toby = new Dog();
const lucy = new Dog();
const luna = new Cat();
toby.breed(lucy); // OK
toby.breed(luna); // Works, but it shouldn't since luna is a Cat!
It appears that TypeScript may be implementing some form of duck typing in this scenario, treating Dog == Cat
. How can I prompt the typechecker to identify and reject this inconsistency?
Sidenote: In Rust, I would handle this situation like so:
trait Mammal { fn breed(&self, other: &Self); } struct Cat {} impl Mammal for Cat { fn breed(&self, _other: &Self) {} } struct Dog {} impl Mammal for Dog { fn breed(&self, _other: &Self) {} } fn main() { let toby = Dog{}; let lucy = Dog{}; let luna = Cat{}; toby.breed(&lucy); toby.breed(&luna); // expected struct `Dog`, found struct `Cat` }