簡體   English   中英

為什么TypeScript在投射時不抱怨狀態中不包含的屬性?

[英]Why does TypeScript not complain about properties not included in the state when casting?

為什么TypeScript會表現出我的情況?

如果我直接鍵入對象,它將抱怨接口中未定義的屬性。 但是,如果我強制轉換為對象,則可以添加接口中未定義的任何隨機屬性。

最好用一個例子解釋一下:

interface House {
  windows: number;
  garden: boolean;
}

const house1: House = {
  windows: 5,
  garden: true,
  garage: true // not allowed
};

const whatever = {
  house2: <House> {
    windows: 3,
    garden: true,
    garage: true // why is it here allowed?
  }
};

之所以有效,是因為它是類型斷言 基本上告訴編譯器是什么類型,但不保護它,例如

const house1 = <House> {
  windows: 5,
  garden: true,
  garage: true // allowed
};

基本上,您告訴ts-compiler不要執行特殊的數據檢查或重組。

您可以使用屬性的適當類型來鍵入衛兵,例如

const whatever: { house2: House } = {
    house2: {
        windows: 3,
        garden: true,
        garage: true // not allowed
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM