Let's suppose that I have the following code:
interface ItemsByKeyInterface {}
interface AType {
key: number;
label: string;
}
const array: AType[] = [
{ key: "a", label: "1" },
{ key: "b", label: "2" }
];
const itemsByKey: ItemsByKeyInterface = array.reduce((total, item) => {
return {
...total,
[item.key]: item
};
}, {});
How should I define ItemsByKeyInterface
properly? Consider that AType could be anything (anything with a key property) and the array could have an unlimited and unknown number of items (consider that key would be unique in that array)
const p = itemsByKey.b.label;
Did you try this
interface ItemsByKeyInterface {
[key: number]: Item;
}
interface Item { key: number; label: "1"| "2"; } interface ItemsByKeyInterface { [key: Item["key"]]: Item; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.