How excess property check helps?

我的梦境 提交于 2019-12-18 08:57:46

问题


For the below code,

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

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?


回答1:


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

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

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.



来源:https://stackoverflow.com/questions/50143250/how-excess-property-check-helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!