Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 361
overexchange Avatar asked May 02 '18 20:05

overexchange


1 Answers

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.

like image 113
Ryan Cavanaugh Avatar answered Sep 22 '22 12:09

Ryan Cavanaugh