国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

javascript - Typescript has a problem with detecting additional properties of interfaces and object literals. Why are additional properties not detected when using assertions or variables?
習(xí)慣沉默
習(xí)慣沉默 2017-06-30 09:52:24
0
2
797
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

習(xí)慣沉默
習(xí)慣沉默

reply all(2)
為情所困

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

洪濤
  1. as is forced type conversion, which forces a variable to be used as another type. You are responsible for any problems during runtime.

  2. 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 };
// 不報(bào)錯(cuò), typeof a 與 SquareConfig 類型兼容
let b: SquareConfig = a; 

// 報(bào)錯(cuò),聲明 c 是 SquareConfig 類型但是給了不存在的屬性
let c: SquareConfig = { colour: "red", width: 100 }; 

// 報(bào)錯(cuò),原因和上面類似
test({ colour: "red", width: 100 })

// 不報(bào)錯(cuò),強(qiáng)制把這個(gè)對(duì)象字面量當(dāng) SquareConfig 類型使用,出問題你自己背鍋
let d: SquareConfig = <SquareConfig> { colour: "red", width: 100 };
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template