Pato Loco
Pato Loco

Reputation: 1244

How to define type or interface for dynamic object?

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;

Upvotes: 1

Views: 45

Answers (1)

MoxxiManagarm
MoxxiManagarm

Reputation: 9134

Did you try this

interface ItemsByKeyInterface {
  [key: number]: Item;
}

Upvotes: 3

Related Questions