Home > Software design >  How do I type an object with multiple child objects that have enum type keys?
How do I type an object with multiple child objects that have enum type keys?

Time:04-22

In TypeScript I have an object like this:

enum MyEnum {
  A = 'A',
  B = 'B',
  C = 'C',
};

type MyData = {
  name: string,
  description: string,
};

const obj = {
  [MyEnum.A]: {
    name: 'one',
    description: 'two',
  } as MyData,
  [MyEnum.B]: {
    name: 'three',
    description: 'four',
  } as MyData,
  // ... etc ... many entries ..
};

console.log( 'value: ', obj[MyEnum.A] );

How do I create a type when the object acts like an array?

const obj: ??? = {
  // ...
};

CodePudding user response:

I would use an index signature. If every member of MyEnum is required to have an entry in the object, this will look like:

const obj: { [key in MyEnum]: MyData } = {
  [MyEnum.A]: {
    title: 'one',
    description: 'two',
  },
  [MyEnum.B]: {
    title: 'three',
    description: 'four',
  },
  // ... etc
}

If only some of MyEnum are present, then you can make it optional:

{ [key in MyEnum]?: MyData }

Playground Link

  • Related