In Typescript, I have encountered the following curiosity when passing a variable of one interface type to a function that expect a parameter of a different interface type.
Lets declare two interfaces, one for a Fruit
and one for a Car
:
interface Fruit { name: string }
interface Car { name: string, wheels: number }
Now, let's declare a method that should do something with a Fruit
only:
function fruitOnly( paramFruit: Fruit ): void {
console.log( paramFruit.name + " is a fruit!" );
}
Finally, let's test it out:
let car: Car = { name: "Carrie the Car", wheels: 4 };
fruitOnly( car );
Result:
Carrie the Car is a fruit!
Question: Why do I not get a warning about car
not being of type Fruit
? (when trying to pass it as a parameter to fruitOnly( paramFruit: Fruit )
?
I was under the impression, the point of TypeScript was to help me not pass parameters of the wrong types? I'm assuming the reason for this is that both interfaces happen to have the name
property. Is there a workaround for this, or is this expected behaviour?
Desired behaviour: I would like to get a warning that I am passing the wrong type to the function.