如何在 React PropTypes 中使用 Typescript Union Type?

Caz*_*tto 3 types typescript reactjs create-react-app react-proptypes

我正在尝试做类似的事情:

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

我收到此错误:

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

两个疑问:

  1. 如何使用 PropTypes 键入它?
  2. 在 TypeScript Create React APP 应用程序中是否有更简单的方法来使用 Typescript 和 PropTypes?

Kar*_*ski 8

string[]使用const 断言['ONE', 'OTHER']将类型范围缩小到:

MyComponent.propTypes = {
  country: PropTypes.oneOf(['ONE', 'OTHER'] as const).isRequired,
};
Run Code Online (Sandbox Code Playgroud)