m1gu3l m1gu3l - 5 months ago 19
Javascript Question

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?

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?

Answer

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 compiler 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;
     }

 }