46

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?} />?

2 Answers 2

62

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} />
Sign up to request clarification or add additional context in comments.

8 Comments

do i need to redefine the enum again in the Component that's rendering Demo?
No, you should be able to import from the module where you defined it as you would any other type
so something like import { Demo, Sizes} from "../src/Demo.tsx"; ?
but when i do SizeEnum.Small i dont get intellisense for small or large
it works if you get rid of the tsx from import { Demo, Sizes} from "../src/Demo.tsx
|
28

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

1 Comment

Would be great with reference to the statement "... considered a bad and unreliable practice in typescript"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.