0
當定義接口時,TypeScript文檔提到,只要對象具有接口的形狀,就允許任何多餘的對象屬性。爲什麼TypeScript只有在使用大括號定義時才允許對象的超額屬性?
一個例子
interface Person {
name: string
}
function print(somebody: Person) {
console.log(somebody.name);
}
let obj = { name: "Johnny", additionalProps: true }
print(obj); // this is okay
但就是這唯一的函數參數是真的嗎?下面我嘗試創建一個對象作爲特定類型進行強制轉換,並且只有當我不使用大括號時,添加其他屬性纔會引發錯誤。
interface Animal {
name: string;
}
let myDog = <Animal> {
name: "Spot",
altProperty: "anything" // no error
};
myDog.altProperty = "anything else"; // Property 'altProperty' does not exist on type 'Animal'
這似乎可以爲你維護其類型時喜歡將對象分配儘可能多的性能,而是因爲他們沒有在類型定義,你不能訪問任何這些。爲什麼是這樣?