Home > Blockchain >  TypeScript: How to initialize object with dynamic keys using index signature?
TypeScript: How to initialize object with dynamic keys using index signature?

Time:11-01

Is it possible to simplify the following so that when I have a new product type, I do not need to add another line of code for the new product type to initialize it? There is syntax error if I do not initialize the variable.

enum ProductType {
   PC = 'pc',
   LAPTOP = 'laptop',
   TV = 'tv'
}

let productList: { [key in ProductType]: Product[] | undefined } = {
  [ProductType.PC]: undefined,
  [ProductType.LAPTOP]: undefined,
  [ProductType.TV]: undefined
}

CodePudding user response:

If only I have understood you correctly, you want to avoid adding new line with every new ProductType for the initialization object, here is one of the possible solutions. Making it more dynamic with reducing over the enum's keys into an object.

enum ProductType {
  PC = 'pc',
  Laptop = 'laptop',
}

const o = Object.values(ProductType).reduce(
   (acc, key) => ({
      ...acc,
      [key]: undefined,
   }),
   {} as Record<ProductType, undefined>
);

// const o = { pc: undefined, laptop: undefined };

CodePudding user response:

I coded it as suggested by VLAZ

let productList: { [key in ProductType]?: UserProduct[] | undefined } = {}
  • Related