6

I'm trying to strict type a Button component in React.

How can I expect a prop with a specific string value?

My current attempt results in Type '"primary"' is not assignable to type 'ButtonLevel'

enum ButtonLevel {
  Primary = "primary",
  Secondary = "secondary",
  Warning = "warning"
}

interface IButtonProps {
  level: ButtonLevel,
  disabled?: boolean
}

function MyButton(props: IButtonProps) {
  return (<Button>ABC</Button>)
}

function test() {
  return (<MyButton level="primary" ></MyButton>)
}

3 Answers 3

7

Right... just enter the values pipe separated

interface IButtonProps {
  level: "primary" | "secondary" | "warning",
  disabled?: boolean
}

function test() {
  return (<MyButton level="ad" disabled >Continue</MyButton>)
}

Which then warns a component consumer the value is invalid.

Sign up to request clarification or add additional context in comments.

Comments

5

you can use ${ButtonLevel} to get ButtonLevel Enum value.

such as

enum ButtonLevel {
  Primary = 'primary',
  Secondary = 'secondary',
  Warning = 'warning',
}

interface IButtonProps {
  level: `${ButtonLevel}`;
// (property) IButtonProps.level: "primary" | "secondary" | "warning"
  disabled?: boolean;
}

function MyButton(props: IButtonProps) {
  return <Button>ABC</Button>;
}

function test() {
  return <MyButton level="primary"></MyButton>;
}

3 Comments

This actually works. I have to admit I was surprised by that. So yes, this is a valid alternative. Although I consider the string literal type solution from the accepted answer as simpler, more straight to the point, less confusing, and therefore preferrable. But -nonetheless- nice answer.
Cool! I didn't know you could do this string interpolation of an Enum to string union!
Depending on how reusable fix you look for, this answer might be better over: level: "primary" | "secondary" | "warning" because it doesn't force you to harcode the literals. In my app I have constants like "pirmary", "secondary" etc used all over and with: level: ${ButtonLevel} everything is centralized in case you should change the literals
3

When you use enum you pass ButtonLevel.Primary not 'primary', the point of enums is to be strongly typed and prevent typos.

Comments

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.