2016-02-05 94 views
3

我讀打字稿手冊,接口的章節中,我發現了一個問題:接口的打字稿

interface LabelledValue { 
    label: string; 
} 

function printLabel(labelledObj: LabelledValue) { 
    console.log(labelledObj.label); 
} 

let myObj = {size: 10, label: "Size 10 Object"}; 
printLabel(myObj); 

printLabel需要一個label:string屬性的對象,但我們傳遞的對象有一個名爲size另一個屬性。這是可以的,因爲編譯器只檢查至少需要的那些是否存在並匹配所需的類型。

但是,我們我稱之爲printLabel這樣:

printLabel({size: 10, label: "Size 10 Object"}); 

的編譯拋出異常。

爲什麼?

+0

你能包括例外嗎? – Igor

+1

如果你想搜索錯誤消息('對象字面量只能指定已知屬性'),你會找到答案:http://stackoverflow.com/questions/31816061/why-am-i-getting-an-錯誤對象字面量可能只指定已知屬性或http://stackoverflow.com/questions/32897098/typescript-object-implementing-interface-with-extra-properties-error –

回答

4

該文件已過時,並且an issue exists to fix it

What's New in TypeScript page

TypeScript 1.6 enforces stricter object literal assignment checks for the purpose of catching excess or misspelled properties. Specifically, when a fresh object literal is assigned to a variable or passed as an argument for a non-empty target type, it is an error for the object literal to specify properties that don't exist in the target type.

的想法是,這是一個很常見的模式是在對象文本作爲選項的包通過。例如:

interface ConnectionOptions { 
    tryHttps?: boolean; 
    url?: string; 
    username?: string; 
    password?: string; 
} 

但所有這些屬性都是可選的。 1.6之前,我會拼錯其中的任何和編譯器會永遠趕不上此錯誤:通過增加一個類型斷言類型

declare function connect(options: ConnectionOptions); 

// Notice the property given is 'tryHTTPS' instead of 'tryHttps'. 
connect({ url: "stackoverflow.com", tryHTTPS: true }); 

可以解決這個總是得到你要指定到:

printLabel({size: 10, label: "Size 10 Object"} as LabelledValue); 
// or... 
printLabel(<LabelledValue>{size: 10, label: "Size 10 Object"});