Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I type an object with multiple child objects that have enum type keys?

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: ??? = {
  // ...
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading