简体   繁体   English

类型检查和泛型

[英]Type checking and generics

Let's say I have an interface: 假设我有一个接口:

interface Comparable<T> {
    equals(other:T):boolean
}

Which then I'm implementing in several classes: 然后我要在几个类中实现:

class Rectangle implements Comparable<Rectangle> {

    equals(other:Rectangle):boolean {
        // logic
        return true;
    }

}

class Circle implements Comparable<Circle> {

    equals(other:Circle):boolean {
        // logic
        return true;
    }

}

Why TypeScript allows for comparing rectangle and circle? 为什么TypeScript允许比较矩形和圆形?

let circle:Circle = new Circle();
let rectangle:Rectangle = new Rectangle();
console.log( circle.equals(rectangle) );

Shouldn't it warn me that I provided incompatible type to circle's equals method? 它不应该警告我为圆的equals方法提供了不兼容的类型吗?

Like JavaScript, TypeScript uses duck typing. 像JavaScript一样,TypeScript使用鸭子类型。 So in your example rectangle and circle are identical. 因此,在您的示例中,矩形和圆形是相同的。

Once these classes add their own implementations the duck typing will fail and the TypeScript compiler will give you errors. 一旦这些类添加了自己的实现,鸭子的输入将失败,并且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;
     }

 } 

Because your Rectangle and Circle are structurally identical, TypeScript treats them as interchangable types (see "duck typing"). 因为您的Rectangle和Circle在结构上是相同的,所以TypeScript将它们视为可互换的类型(请参阅“鸭子类型”)。 Just flesh out your circle and rectangle by adding some mutually incompatible properties to them: 只需通过向它们添加一些互不兼容的属性来充实您的圆形和矩形即可:

class Rectangle implements Comparable<Rectangle> {
    x: number;
    equals(other:Rectangle):boolean {return true;}
}
class Circle implements Comparable<Circle> {
    rad: number;
    equals(other:Circle):boolean {return true;}
}

And you'll see the error show up. 而且您会看到错误显示。 This is, incidentally, the same reason that you can assign an object literal to a Circle-typed var, as long as it has the right properties: 顺便说一句,这是可以将对象文字分配给Circle型var的相同原因,只要它具有正确的属性即可:

var c: Circle = {rad: 1, equals: () => true}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM