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 to use enum as an object key?

How to use enum as an object key?

Global enum

export enum TableType {
    RawMedias = 'raw-medias',
    Datasets = 'datasets',
    VideosDst = 'videos-dst',
  }

VideoDstPage (parent component)

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

<VideosDstTable data={RAW_MEDIA_DATA} type={TableType.VideosDst} />

VideosDstTable.tsx

interface IVideosDstTableProps {
  type: TableType;
}

const tableHeaders = {
  [TableType.RawMedias]: [
    { id: 1, name: 'Name' },
    { id: 2, name: 'Status' },
  ],
  [TableType.Datasets]: [
    { id: 1, name: 'Name' },
    { id: 2, name: 'Status' },
  ],
  [TableType.VideosDst]: [
    { id: 1, name: 'Name' },
    { id: 2, name: 'Status' },
  ],
};

// ...some code
<Table tableHeaders={tableHeaders[type]}> // here's error

error

Element implicitly has an ‘any’ type because expression of type ‘any’
can’t be used to index type

Table.tsx

interface ITableProps {
  children: JSX.Element;
  tableHeaders: {
    id: number;
    name: string;
  }[];
}

>Solution :

Enums can be used as object keys in TypeScript by casting them to strings.

This can be done by using the toString() method on the enum instance. For example:
let myObject = {[MyEnum.Value1.toString()]: 'value1'};

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