I am grappling with how to properly incorporate typescript typings for the response object received from a backend service:
{
de49e137f2423457985ec6794536cd3c: {
productId: 'de49e137f2423457985ec6794536cd3c',
title: 'item 1',
},
d6623c1a2b843840b14c32685c212395: {
productId: 'd6623c1a2b843840b14c32685c212395',
title: 'item 2',
},
ids: [
'de49e137f2423457985ec6794536cd3c',
'd6623c1a2b843840b14c32685c212395',
],
}
This response object contains an array of item ids string[] and an index signature [id: string]: Item.
Trying to define this in Typescript is proving tricky because having both the index signature and array together in one interface causes issues. For instance:
interface ItemList {
[id: string]: Item;
ids: string[];
}
I understand that when using an index signature, all other properties need to have the same type. As I navigate through Typescript, I am uncertain about how to handle this data structure without extracting the ids out of the item object.
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]));
Error Message
The property 'map' is not found on type 'Item | string[]'.
The property 'map' is not found on type 'Item'.