typescript - 超额属性(property)检查有何帮助?

标签 typescript ecmascript-6 duck-typing

对于下面的代码,

interface SquareConfig{
    color?: string;
    width?: number;
}

interface Square{
    color: string;
    area: number;
}

function createSquare(config: SquareConfig): Square {

    let newSquare:Square = {color: "white", area: 100};
    if (config.color) {
        newSquare.color = config.color;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

below argument(myObj) 被推断为类型 any 在编译时被类型检查器允许作为参数传递。 JS 代码在运行时使用鸭子类型(duck typing)。

let myObj = {colour: 'red', width: 100};

let mySquare = createSquare(myObj);

在第二种情况下,以下参数(SquareConfig 类型除外)在编译时不允许通过类型检查器。正如手册中所述:对象文字在将它们分配给其他变量或将它们作为参数传递时会得到特殊处理并进行额外的属性检查。

let mySquare = createSquare({colour: 'red', width: 100});

第二种情况下超额属性(property)检查的目的是什么?

最佳答案

What is the purpose of excess property check, in second case?

它可以正确检测错误(如本例所示,color 的拼写错误)而不会产生太多误报。

因为该对象在其他任何地方都没有别名,所以 TypeScript 可以相当确信多余的属性不会在代码的其他部分用于不同的目的。 myObj 就不是这样了——我们可能在这里只检查它的 .width,然后在其他地方使用它的 .colour .

关于typescript - 超额属性(property)检查有何帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53194295/

相关文章:

javascript - 使用 React 路由器 React 中间件身份验证组件

python - 鸭子类型(duck typing)与基于类的继承

TypeScript 编译选项 : module vs target

javascript - RXJS5 像 Promise 一样链接

javascript - topojson 未捕获类型错误 : Cannot read property 'feature' of undefined

javascript - 类构造函数中的异步数据加载

Java 泛型对类的工作方式似乎与对方法的工作方式不同

ruby - 子类化核心 Ruby 类,例如 Hash

angular - 如何创建响应调整大小的基于 Angular 2 Canvas 的组件?

javascript - 我如何比较日期字符串?