Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何在类型中使用Typescript联合类型?_Reactjs_Typescript_Types_Create React App_React Proptypes - Fatal编程技术网

Reactjs 如何在类型中使用Typescript联合类型?

Reactjs 如何在类型中使用Typescript联合类型?,reactjs,typescript,types,create-react-app,react-proptypes,Reactjs,Typescript,Types,Create React App,React Proptypes,我正在尝试做这样的事情: 接口道具扩展了RouteComponentProps{ 国家:“一个”另一个; } MyComponent.propTypes={ 国家/地区:PropTypes.['ONE','OTHER']之一。需要, }; 我收到这个错误: Type 'Validator<string>' is not assignable to type 'Validator<"ONE" | "OTHER">'. Type '

我正在尝试做这样的事情:

接口道具扩展了RouteComponentProps{ 国家:“一个”另一个; } MyComponent.propTypes={ 国家/地区:PropTypes.['ONE','OTHER']之一。需要, }; 我收到这个错误:

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

如何使用PropTypes键入它? 在Typescript创建应用程序中,有一种更简单的方法可以同时使用Typescript和PropTypes?
使用Typescript时,有一些工具可用于将类型转换为其PropTypes等效项

工具,如:

如果有人想知道为什么要将PropTypes与Typescript一起使用,请使用以下命令将类型从string[]缩小到['ONE','OTHER']:


为什么你要在使用Typescript的同时使用proptypes?@guy不知道它们并不矛盾,你可以而且有时应该同时使用它们。如果你使用Typescript,就不需要使用proptypes。两者都使用是很好的。如果您正在使用库,那么代码的使用者可能正在使用JavaScript,而PropTypes是他们验证其Prop的唯一方法。此外,PropTypes可以检测导致渲染浪费的多余属性。这应该在PropTypes的官方文档中注明!小时!
MyComponent.propTypes = {
  country: PropTypes.oneOf(['ONE', 'OTHER'] as const).isRequired,
};