【问题标题】:Interface in TypeScriptTypeScript 中的接口
【发布时间】:2016-02-05 15:39:22
【问题描述】:

我在看Typescript手册,在界面一章发现了一个问题:

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】:

文档已过时,an issue exists to fix it

来自What's New in TypeScript page

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"});

【讨论】:

    猜你喜欢
    • 2017-12-17
    • 2017-04-09
    • 2014-07-25
    • 2021-08-17
    • 2016-06-26
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多