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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…