![](/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.