我想要一個由字串型別的 id 索引并具有字串值的物件。
這是我的界面:
interface Bars {
[id: string]: string;
}
下面看到的bars物件是一個物件陣列,其中鍵是 reducer 中的字串 ( barId) 和字串值 ( myVal)。
const bars = barsResponse.bar.reduce((acc, bar) => {
acc[bar.barId as string] = bar.myVal;
return acc;
}, {});
我在這里做錯了什么,TypeScript 正在大喊:
Element implicitly has 'any' type because expression of type 'any' can't be used to index type '{}'
uj5u.com熱心網友回復:
您必須為累加器引數或默認回傳值分配一個型別
reduce((acc:Bars, bar) => {...}
const bars = bar.reduce((acc, bar) => {
acc[bar.barId as string] = bar.myVal;
return acc;
}, {} as Bars);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516212.html
標籤:打字稿
上一篇:使用條件屬性擴展現有物件
