Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using typescript enum and react to expect string prop

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>)
}
like image 373
Lex Avatar asked Aug 30 '26 21:08

Lex


1 Answers

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.

like image 134
Lex Avatar answered Sep 01 '26 14:09

Lex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!