2

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?
Cazetto
  • 51
  • 1
  • 6

2 Answers2

7

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

MyComponent.propTypes = {
  country: PropTypes.oneOf(['ONE', 'OTHER'] as const).isRequired,
};
Karol Majewski
  • 23,596
  • 8
  • 44
  • 53
0

When working with Typescript, there are tools for converting types to their PropTypes equiviliants.

Tools like:

For anyone who wonders why you should use PropTypes with Typescript, read here.

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118