超额财产检查有何帮助?

问题描述:

对于下面的代码,

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 代码在运行时使用鸭子类型.

below argument(myObj) inferred as type any is allowed to pass as argument by type checker at compile time. JS code use duck typing at runtime.

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

let mySquare = createSquare(myObj);

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

In second case, below argument(other thanSquareConfig type) is not allowed to pass by type checker at compile time. As mentioned in handbook: Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments.

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

在第二种情况下,超额财产检查的目的是什么?

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

在第二种情况下,超额财产检查的目的是什么?

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

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

It correctly detects bugs (as shown in this case, the misspelling of color) without creating too many false positives.

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

Because the object isn't aliased anywhere else, TypeScript can be fairly confident that the excess property isn't going to be used for a different purpose in some other part of the code. The same cannot be said of myObj - we may be inspecting it only for its .width here but then using its .colour in some other place.