How to use enum as an object key?

Advertisements

How to use enum as an object key?

Global enum

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

VideoDstPage (parent component)

<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'};

Leave a ReplyCancel reply