简体   繁体   English

类型在Typescript中是结构性的。 对象文字的问题

[英]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.

相关问题 打字稿。 如何指定对象文字属性的子集类型? - Typescript. How to specify a type of a subset of object literal properties? d3 和 Typescript。 selection.merge 类型问题 - d3 and Typescript. selection.merge types problem 打字稿。 正确键入依赖于同一对象文字中属性的函数参数 - Typescript. Correctly typing function parameter that depends on property in the same object literal TypeScript中对象文字符号内的函数。 为什么`this`上下文是`any`类型的? - Functions within object literal notation in TypeScript. Why `this` context is of type `any`? 打字稿。 TSLint在类型中不起作用 - TypeScript. TSLint does not wok in Types 打字稿中所有对象文字类型的子类型? - Subtype of all object literal types in typescript? 打字稿。 数组中不兼容的类型。 如何使用可以获取任何对象数组的方法声明对象? - TypeScript. incompatible types in array. How to declare an object with method that can take array of any objects? Typescript 中出现异常“查找”错误。 为什么; 有问题吗? - Unusual "find" error in Typescript. Why ; is a problem? Typescript。 在嵌套的 object 中动态添加属性 - Typescript. Dynamically add property in nested object `Object.entries().map()` 不会在打字稿上保留类型。 如何改进我的界面以使其正常工作? 或解决方法? - `Object.entries().map()` don't preserve types on typescript. How can I improve my interface for it to work? or workaround?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM