Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeScript中的接口_Typescript - Fatal编程技术网

TypeScript中的接口

TypeScript中的接口,typescript,Typescript,我正在阅读打字本手册,在界面一章中,我发现了一个问题: interface LabelledValue { label: string; } function printLabel(labelledObj: LabelledValue) { console.log(labelledObj.label); } let myObj = {size: 10, label: "Size 10 Object"}; printLabel(myObj); printLabel需要一个具有labe

我正在阅读打字本手册,在界面一章中,我发现了一个问题:

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"});
编译抛出一个异常


那么,为什么呢?

文档已经过时,而且已经过时

从:

TypeScript 1.6强制执行更严格的对象文字赋值检查,以捕获多余或拼写错误的属性。具体地说,当一个新对象文本被分配给一个变量或作为非空目标类型的参数传递时,对象文本指定目标类型中不存在的属性是错误的

这是一种非常常见的模式,将对象文本作为一包选项传入。例如:

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"});
printLabel({size:10,label:“size 10 Object”}作为LabelledValue);
//或者。。。
printLabel({size:10,label:“size 10 Object”});

您可以包括异常吗?如果您搜索错误消息(
对象文字可能只指定已知属性),您将找到答案:或