![](/img/trans.png)
[英]Typescript. How to specify a type of a subset of object literal properties?
[英]Types are structural in Typescript. Problem with object literal
摘自《 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`
我替换此行:
iTakePoint2D(point3D); // extra information okay
与
iTakePoint2D({ x: 0, y: 10, z: 20 });
我有一个错误。 为什么现在多余的信息行不通?
当将对象文字分配给其他类型或将它们作为参数传递给函数时,它们总是经过多余的属性检查。
https://www.typescriptlang.org/docs/handbook/interfaces.html#excess-property-checks
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.