typescript - TypeScript 中的接口(interface)

标签 typescript

我在看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/

相关文章:

TypeScript:元组类型到对象类型

基于第一项数组的值的数组第二项的 typescript 值

javascript - 组成 Type Script 项目的多个文件

typescript - typescript 签名中的函数获取 setter

javascript - typescript 和 AngularJS 1.5 : How to handle export class

typescript - 当我不在异步函数中返回 Promise 时,为什么 typescript 不提示

用于保存对 HTML5 Canvas 的 Jquery 引用的 Typescript 变量

typescript - 强制 IDE 使用 Webpack 解析 Typescript 模块的别名

javascript - 扩展 typescriptdefineTyped 定义文件

typescript - TypeScript 如何检查无限递归类型的相等性?