最近学习 typescript
时遇到了一点疑惑, 如下:
class Cat {
speak() {
console.log('cat')
}
}
class Dog implements Animal {
speak() {
console.log('dog')
}
}
interface Animal {
speak(): void
}
function sayIt(animal: Animal) {
animal.speak()
}
sayIt(newCat()) // cat
sayIt(newDog()) // dog
Cat
这个类似乎并没有实现Animal
这个接口, 但仍然可以正确输出. 尽管Cat
拥有speak()
方法, 但这样做是否违背了多态的本意? 感觉更像是 duck type
. 而对于Dog
实现了Animal
接口, 和预期一样得到了结果.
如果 duck type 存在的话, 接口存在的意义又是什么?
本人使用的 typescript 版本为3.7.2
, 且均在严格模式下.
望能有前辈解答, 多谢!
https://www.tslang.cn/docs/handbook/type-compatibility.html