我讀打字稿手冊,接口的章節中,我發現了一個問題:接口的打字稿
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"});
的編譯拋出異常。
爲什麼?
你能包括例外嗎? – Igor
如果你想搜索錯誤消息('對象字面量只能指定已知屬性'),你會找到答案:http://stackoverflow.com/questions/31816061/why-am-i-getting-an-錯誤對象字面量可能只指定已知屬性或http://stackoverflow.com/questions/32897098/typescript-object-implementing-interface-with-extra-properties-error –