Here I get an error which I understand
interface Animal {
name:string
}
interface Human{
firstName:string
}
let test = (param: Animal )=>{
if("name" in param)
return param.name
return param.firstName
}
console.log(test({name:"1", firstName:"2"}))
because Animal
doesn't have firstName
.
As soon as I modify that function to
let test = (param: Animal | Human)=>{
if("name" in param)
return param.name
return param.firstName
}
the error is gone.
But I am confused. Doesn't |
mean that the param
is either Animal
or Human
?
But {name:"1", firstName:"2"}
is neither isn't it? (Like in the first example TS wasn't accepting this as an Animal
).
Bonus question also from the docs it says here it is not an error
interface Pet {
name: string;
}
let pet: Pet;
// dog's inferred type is { name: string; owner: string; }
let dog = { name: "Lassie", owner: "Rudd Weatherwax" };
pet = dog;
because dog
has more properties than a Pet
. But why did it complain in my initial case when I passed the object as Animal
? it had more properties, isn't it?