Here is an example using TypeScript:
interface Animal{
eat():void;
sleep():void;
}
class Mammal implements Animal{
constructor(private name:string){
console.log(this.name, "is alive");
}
eat(){
console.log("Like a mammal");
}
sleep(){
console.log("Like a mammal");
}
}
class Dog extends Mammal{
eat(){
console.log("Like a dog")
}
}
let m: Mammal = new Dog("Prisca"); // This seems correct
let d: Dog = new Mammal("abomination"); // This works too
For variable d
, TypeScript uses Structural typing, so type Dog
inherits properties from Mammal
. Variable d
can reference objects of type Mammal
until a new property is added to type Dog
.
In TypeScript, how can we prevent these pitfalls?