Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Typescript Union Type in React PropTypes?

I am trying to do something like that:

interface Props extends RouteComponentProps {
  country: 'ONE' | 'OTHER;
}
MyComponent.propTypes = {
  country: PropTypes.oneOf(['ONE', 'OTHER']).isRequired,
};

And I am receiving this error:

Type 'Validator<string>' is not assignable to type 'Validator<"ONE" | "OTHER">'.
  Type 'string' is not assignable to type '"ONE" | "OTHER"'.ts(2322)

Two doubts:

  1. How can I type it using PropTypes?
  2. There is a simpler way to work with both Typescript and PropTypes in a TypeScript Create React APP application?
like image 929
Cazetto Avatar asked Oct 23 '25 13:10

Cazetto


1 Answers

Narrow the type from string[] to ['ONE', 'OTHER'] using a const assertion:

MyComponent.propTypes = {
  country: PropTypes.oneOf(['ONE', 'OTHER'] as const).isRequired,
};
like image 163
Karol Majewski Avatar answered Oct 26 '25 04:10

Karol Majewski



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!