typescript - 正确处理 TypeScript 的弱类型检测
问题描述
鉴于这个简化的例子,表达该函数makeAnimalBark
可以接受任何动物但只会让吠叫的动物吠叫的正确方法是什么?
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: () => { }
})
我理解为什么我会看到错误,但我不确定处理这种情况的正确方法。
解决方案
// Without `A` extending from something that has a `bark`
// property, TS complains that `bark` doesn't exist on `A`.
那是因为您输入bark
的内容是可选的
interface PotentiallyBarkingAnimal {
// remove the ? to make bark mandatory
bark?: () => void
}
// Here, TS complains that `Cat` has no properties
// in common with `PotentiallyBarkingAnimal`.
那是真的,对吧?如果您查看它Cat
的界面,它没有bark
与PotentiallyBarkingAnimal
. 您需要PotentiallyBarkingAnimal
告知meow
.