4

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?
4
  • 4
    Why are you using proptypes at the same time with Typescript? Commented Jun 24, 2020 at 19:52
  • @GuyIncognito they not contradict, you can and sometimes should use them both. Commented Jun 24, 2020 at 20:00
  • 1
    If you're using TypeScript, there's no need for PropTypes. Commented Jun 24, 2020 at 20:16
  • 3
    It's perfectly fine to use both. If you're working on a library, the consumers of your code may be using JavaScript — and PropTypes is the only way for them to validate their props. Also, PropTypes can detect excess properties that cause wasted renders. Commented Jul 1, 2020 at 14:15

2 Answers 2

8

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

MyComponent.propTypes = {
  country: PropTypes.oneOf(['ONE', 'OTHER'] as const).isRequired,
};
Sign up to request clarification or add additional context in comments.

1 Comment

this should be noted in the official docs of propTypes! hours!
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.

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.