[英]Types are structural in Typescript. Problem with object literal
From book Basarat - TypeScript Deep Dive 摘自《 Basarat-TypeScript深入学习
interface Point2D {
x: number;
y: number;
}
interface Point3D {
x: number;
y: number;
z: number;
}
var point2D: Point2D = { x: 0, y: 10 }
var point3D: Point3D = { x: 0, y: 10, z: 20 }
function iTakePoint2D(point: Point2D) { /* do something */ }
iTakePoint2D(point2D); // exact match okay
iTakePoint2D(point3D); // extra information okay
iTakePoint2D({ x: 0 }); // Error: missing information `y`
I replace this line: 我替换此行:
iTakePoint2D(point3D); // extra information okay
with 与
iTakePoint2D({ x: 0, y: 10, z: 20 });
and I have an Error. 我有一个错误。 Why is now extra information not okay? 为什么现在多余的信息行不通?
Object literals always undergo excess property checks when they are assigned to other types or they are passed as an argument to a function. 当将对象文字分配给其他类型或将它们作为参数传递给函数时,它们总是经过多余的属性检查。
https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.