假设我有一个界面:
interface Comparable<T> {
equals(other:T):boolean
}
然后我在几个类中实现:
class Rectangle implements Comparable<Rectangle> {
equals(other:Rectangle):boolean {
// logic
return true;
}
}
class Circle implements Comparable<Circle> {
equals(other:Circle):boolean {
// logic
return true;
}
}
为什么 TypeScript 允许比较矩形和圆形?
let circle:Circle = new Circle();
let rectangle:Rectangle = new Rectangle();
console.log( circle.equals(rectangle) );
它不应该警告我我为 circle 的equals 方法提供了不兼容的类型吗?
最佳答案
与 JavaScript 一样,TypeScript 使用鸭子类型(duck typing)。因此,在您的示例中,矩形和圆形是相同的。
一旦这些类添加了自己的实现,duck typing 就会失败,TypeScript 编译器就会报错。
class Rectangle implements Comparable<Rectangle> {
width: number;
height: number;
equals(other:Rectangle): boolean {
// logic
return true;
}
}
class Circle implements Comparable<Circle> {
diameter: number;
equals(other:Circle): boolean {
// logic
return true;
}
}
关于javascript - 类型检查和泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37728309/