interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig): { color: string; area: number } {
// ...
}
let mySquare = createSquare({ colour: "red", width: 100 });
ts An error will be thrown when compiling this code, but it will not be thrown by using the following two methods. What is the principle? The explanation on the official website is beyond my comprehension. It only makes me feel that ts syntax is so casual...
let mySquare = createSquare({ width: 100, opacity: 0.5 } as SquareConfig);
or
let squareOptions = { colour: "red", width: 100 };
let mySquare = createSquare(squareOptions);
No error will be reported in this way. When using assertions (as/<>), will the interface be compared according to what rules? Then copy the object literal to the variable. I know this is a reference pointer to the object, but why won't the additional properties be detected? Official website address
The first example:
as
It’s not an assertion, right?as
It’s a forced conversion, which means you know what you want to do. Of course, ts will let you compile it.The second example seems to have been done originally, right?
color
You don’t have to;colour
is another attributeThe reason why it was not used before is that ts has a unique check for object literals
as is forced type conversion, which forces a variable to be used as another type. You are responsible for any problems during runtime.
The detection logic of using object literals to assign objects is different from the mechanism of using variables to assign objects.