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
为情所困2017-06-30 09:54:24
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 attribute
The reason why it was not used before is that ts has a unique check for object literals
PHP中文网2017-06-30 09:54:24
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.
interface SquareConfig {
color?: string;
width?: number;
}
function test(config: SquareConfig): void {}
let a = { colour: "red", width: 100 };
// 不报错, typeof a 与 SquareConfig 类型兼容
let b: SquareConfig = a;
// 报错,声明 c 是 SquareConfig 类型但是给了不存在的属性
let c: SquareConfig = { colour: "red", width: 100 };
// 报错,原因和上面类似
test({ colour: "red", width: 100 })
// 不报错,强制把这个对象字面量当 SquareConfig 类型使用,出问题你自己背锅
let d: SquareConfig = <SquareConfig> { colour: "red", width: 100 };