我在看Typescript handbook,在interface那一章,我发现了一个问题:
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);
printLabel
需要一个具有label:string
属性的对象,但是我们传递的对象有另一个名为size
的属性。没关系,因为编译器只检查是否至少存在所需的类型并匹配所需的类型。
但是,我们以这种方式调用 printLabel
:
printLabel({size: 10, label: "Size 10 Object"});
编译抛出异常。
为什么?
最佳答案
文档已过时且an issue exists to fix it .
来自What's New in TypeScript page :
TypeScript 1.6 enforces stricter object literal assignment checks for the purpose of catching excess or misspelled properties. Specifically, when a fresh object literal is assigned to a variable or passed as an argument for a non-empty target type, it is an error for the object literal to specify properties that don't exist in the target type.
这个想法是一个非常常见的模式是将对象文字作为选项包传递。例如:
interface ConnectionOptions {
tryHttps?: boolean;
url?: string;
username?: string;
password?: string;
}
但是所有这些属性都是可选的。在 1.6 之前,我可能会拼错其中任何一个,编译器永远不会捕获此错误:
declare function connect(options: ConnectionOptions);
// Notice the property given is 'tryHTTPS' instead of 'tryHttps'.
connect({ url: "stackoverflow.com", tryHTTPS: true });
您始终可以通过向要分配给的类型添加类型断言来解决此问题:
printLabel({size: 10, label: "Size 10 Object"} as LabelledValue);
// or...
printLabel(<LabelledValue>{size: 10, label: "Size 10 Object"});
关于typescript - TypeScript 中的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35227989/