Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use enum as props in react/typescript

I have the following enum

export enum Sizes{
    Small,
    Large
}

which is getting used in my <Demo/> component's props interface:

export interface IProps{
    Label?: string;
    Size: SizeEnum;
}

My question is, when I use this <Demo Size={how do i define size here?} />?

like image 912
blankface Avatar asked Apr 10 '18 06:04

blankface


2 Answers

You can just reference the enum value as you would in any other context:

export enum Sizes{     Small,     Large }  export interface IProps{     Label?: string;     Size: Sizes; }  class Demo extends React.Component<IProps> {}  let d = <Demo Size={Sizes.Large} /> 
like image 87
Titian Cernicova-Dragomir Avatar answered Sep 20 '22 00:09

Titian Cernicova-Dragomir


Use type or as const

Both type and as const have auto-fill and will complain when an invalid value is used.

type

'up'   

Implement with:

type MyEnum = 'up' | 'down' | 'left' | 'right'

interface IProps {
  Size: MyEnum
}

as const

MyEnum.Up    

Implement with:

const MyEnum = {
  Up: 'up',
  Down: 'down',
  Left: 'left',
  Right: 'right',
} as const

type MyEnum = typeof MyEnum[keyof typeof MyEnum]

// Example type
interface IProps {
  Size: MyEnum // string, without line `type MyEnum =...`
}

More detail on as const and freezing parameters

like image 42
Gibolt Avatar answered Sep 20 '22 00:09

Gibolt