2017-07-21 11 views
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' 

這似乎可以爲你維護其類型時喜歡將對象分配儘可能多的性能,而是因爲他們沒有在類型定義,你不能訪問任何這些。爲什麼是這樣?

回答

1

typescript中的接口僅提供編譯時檢查,以解釋對象上可用的成員。

您的代碼在這裏:

let myDog = <Animal> 

是說:「我有一些對象,但我想只露出由Animal接口定義的成員」。您已明確告知編譯器會在您引用未在Animal中定義的成員時爲您提供錯誤。

創建對象時,您可以引用altProperty,因爲您尚未爲其指定類型。但是,是你寫的:

let myDog: Animal = { 
    //name: "Spot", 
    altProperty: "anything" // no error 
}; 

你會得到一個錯誤的嘗試投無效對象Animal

現在,您不需要對象轉換爲Animal才能夠使用它是這樣的。你可以這樣寫:

interface Animal { 
    name: string; 
} 

let myDog = { 
    name: "Spot", 
    altProperty: "anything" 
}; 

myDog.altProperty = "anything else"; 

doSomething(myDog); 
function doSomething(object: Animal) {} 

它會正常工作。事實上,明確鍵入像你所做的變量的唯一原因是故意捕捉你遇到的錯誤。

相關問題