2017-05-24 25 views
1

我有一個接口foobar,它有兩個屬性「number」。 現在我嘗試將foobar類型的對象匹配到通用對象定義,其中每個屬性都是類型編號。接口與TypeScript中的通用對象不匹配

interface foobar { 
    a: number, 
    b: number 
} 

function baz(param: {[key: string]: number}) { 
    // some math stuff here 
} 

const obj: foobar = { 
    a: 1, 
    b: 2 
}; 

baz(obj); // error happens here 

這會導致以下TypeScript錯誤。

TS2345:'foobar'類型的參數不能分配給類型爲'{[key:string]:number; }」。在'foobar'類型中缺少索引簽名。

有沒有什麼辦法可以將對象與接口匹配到只有類型數值的通用對象?

+0

值得一讀https://stackoverflow.com/questions/22077023/why-cant-i-indirectly-return-an-object-literal-to-satisfy-an-index-signature-re –

回答

1

有沒有什麼辦法可以將對象與接口匹配到只有類型數值的通用對象?

號打字稿不知道,你不這樣寫:

// OK: This is legal code 
const obj1 = { a: 1, b: 2, c: "oops" }; 
// OK: Structural type matches 
const obj: foobar = obj1; 
// Crash when baz sees c: "oops" 
baz(obj); // error happens here 

在這種情況下,最好的辦法是剛剛從該行刪除類型標註:

const obj = { 
    a: 1, 
    b: 2 
}; 

因爲它是用對象文字初始化的const,所以TypeScript知道沒有任何其他屬性留在對象上,所以使用索引簽名的地方是安全的(r)。添加一個類型註釋會導致該行爲失敗。