我不确定为我从后端服务接收的响应对象添加打字稿类型的最佳方法:
{
de49e137f2423457985ec6794536cd3c: {
productId: 'de49e137f2423457985ec6794536cd3c',
title: 'item 1',
},
d6623c1a2b843840b14c32685c212395: {
productId: 'd6623c1a2b843840b14c32685c212395',
title: 'item 2',
},
ids: [
'de49e137f2423457985ec6794536cd3c',
'd6623c1a2b843840b14c32685c212395',
],
}
它包含一个项目 id 数组string[]以及索引签名[id: string]: Item。
Typescript 似乎不喜欢在单个界面中拥有索引签名和数组。例如:
interface ItemList {
[id: string]: Item;
ids: string[];
}
我知道在使用索引签名时,其他属性需要返回相同的类型。我是 Typescript 的新手,我有点不确定如何在不将ID从项目对象中移出的情况下使用这些数据?
interface ItemList {
[id: string]: Item;
ids: string[];
}
interface Item {
productId: string;
title: string;
}
const item: ItemList = {
de49e137f2423457985ec6794536cd3c: {
productId: 'de49e137f2423457985ec6794536cd3c',
title: 'item 1',
},
d6623c1a2b843840b14c32685c212395: {
productId: 'd6623c1a2b843840b14c32685c212395',
title: 'item 2',
},
ids: [
'de49e137f2423457985ec6794536cd3c',
'd6623c1a2b843840b14c32685c212395',
],
};
console.log(item.ids.map((id: string) => item[id]));
错误
类型“项目”上不存在属性“地图”| 细绳[]'。
“项目”类型上不存在属性“地图”。