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 badges2 Answers
Reset to default 9Like 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
版权声明:本文标题:javascript - Type checking and generics - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744961447a2634677.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论