Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

typescript - How excess property check helps?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...