How to use Typescript Union Type in React PropTypes?
我正在尝试执行以下操作:
1 2 3 4 5 6 | interface Props extends RouteComponentProps { country: 'ONE' | 'OTHER; } MyComponent.propTypes = { country: PropTypes.oneOf(['ONE', 'OTHER']).isRequired, }; |
我收到此错误:
1 2 | Type 'Validator<string>' is not assignable to type 'Validator<"ONE" |"OTHER">'. Type 'string' is not assignable to type '"ONE" |"OTHER"'.ts(2322) |
两个疑问:
使用const断言将类型从
1 2 3 | MyComponent.propTypes = { country: PropTypes.oneOf(['ONE', 'OTHER'] as const).isRequired, }; |
使用Typescript时,有一些工具可以将类型转换为它们的
类似的工具:
-
babel-plugin-typescript-to-proptypes -
prop-types-ts
对于任何想知道为什么应该将PropTypes与Typescript一起使用的人,请阅读此处。