Reputation: 871
Given this simplified example, what's the proper way to express that the function makeAnimalBark
can accept any animal but only makes the barking ones bark.
interface Dog {
bark: () => void
}
interface Cat {
meow: () => void
}
interface PotentiallyBarkingAnimal {
bark?: () => void
}
// Without `A` extending from something that has a `bark`
// property, TS complains that `bark` doesn't exist on `A`.
function makeAnimalBark<A extends PotentiallyBarkingAnimal>(animal: A) {
if (animal && animal.bark)
animal.bark()
}
makeAnimalBark<Dog>({
bark: () => { }
})
// Here, TS complains that `Cat` has no properties
// in common with `PotentiallyBarkingAnimal`.
makeAnimalBark<Cat>({
meow: () => { }
})
I understand why I'm seeing the error but I'm not sure as to the right way to handle this type of situation.
Upvotes: 0
Views: 110
Reputation: 335
// Without `A` extending from something that has a `bark`
// property, TS complains that `bark` doesn't exist on `A`.
That is because you are typing bark
as being optional
interface PotentiallyBarkingAnimal {
// remove the ? to make bark mandatory
bark?: () => void
}
// Here, TS complains that `Cat` has no properties
// in common with `PotentiallyBarkingAnimal`.
Well that's true, right? if you look at it Cat
s interface, it has no shared properties (bark
) with PotentiallyBarkingAnimal
. You need to let PotentiallyBarkingAnimal
know about meow
.
Upvotes: 1