I was wondering why does not typescript compiler throw error on code below:
interface Greetings {
greeting: string;
}
class Human implements Greetings {
greeting: string = "Why hello there";
}
class Lion implements Greetings {
greeting: string = "Roar";
}
class Lemon {
greeting: string = "I'M A LEMON";
}
class LivingSpecies {
private species: Greetings;
public greet() {
console.log(this.species.greeting)
}
constructor(species: Greetings) {
this.species = species;
}
}
const species1 = new LivingSpecies(new Human())
species1.greet(); // "Why hello there"
const species2 = new LivingSpecies(new Lion())
species2.greet(); // "Roar"
const species3 = new LivingSpecies(new Lemon()) // Why compiler does not complain here?
species3.greet(); // "I'M A LEMON" <--- Why?
For the first two cases it works as intended, both classes implement Greetings
interface, and LivingSpecies
constructor requires class that implements it. But Lemon
class "passes" the constructor parameter as if it implements Greetings
interface. Could you explain this? Thank you.