admin管理员组

文章数量:1406012

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 paring rectangle and circle?

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

Shouldn't it warn me that I provided inpatible type to circle's equals method?

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 paring rectangle and circle?

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

Shouldn't it warn me that I provided inpatible type to circle's equals method?

Share Improve this question edited Jun 9, 2016 at 14:44 m1gu3l asked Jun 9, 2016 at 14:07 m1gu3lm1gu3l 7731 gold badge6 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Like JavaScript, TypeScript uses duck typing. So in your example rectangle and circle are identical.

Once these classes add their own implementations the duck typing will fail and the TypeScript piler will give you errors.

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"). Just flesh out your circle and rectangle by adding some mutually inpatible 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:

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

本文标签: javascriptType checking and genericsStack Overflow