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'類型中缺少索引簽名。
有沒有什麼辦法可以將對象與接口匹配到只有類型數值的通用對象?
值得一讀https://stackoverflow.com/questions/22077023/why-cant-i-indirectly-return-an-object-literal-to-satisfy-an-index-signature-re –