Let's say we have an interface Animal
interface Animal {
amountOfLegs: number;
}
And then two different classes implement this interface, Dog and Snake:
class Dog implements Animal {
constructor(public amountOfLegs: number) {
}
}
class Snake implements Animal {
amountOfLegs: number;
constructor() {
this.amountOfLegs = 0;
}
}
Then we want to create a function that is specific to the Snake:
function functionSpecificForSnake(snake: Snake): any {
//Do something with the snake object...
}
But when the function is called with a Dog object, TS doesn't complain about wrong types:
functionSpecificForSnake(new Dog(4)); // No compiler error, but possible runtime error?
So my question is: Can i prevent this behavior? I know that this is called type compatibility, but i don't see a way to prevent it. Using the "strictFunctionTypes": true option in my tsconfig.json doesn't seem to do anything.