React 中带有 PropTypes 的 Typescript 会抛出枚举错误

Typescript with PropTypes in React throws error with enums

我在为字符串枚举器定义 PropTypes 时遇到了一些问题。我在 Typescript 中有以下类型:

state: "pending"|"accepted"|"rejected",

和对应的propType:

state: PropTypes.oneOf(["pending","accepted","rejected"]).isRequired,

然而,这会引发以下错误:“类型 'string' 不可分配给类型‘‘待定’|‘接受’|‘拒绝’.ts(2322)”。我真的不知道该怎么办!在此先感谢您能给我的任何帮助。

问题是 statetype "pending"|"accepted"|"rejected" 并且它不是枚举它的联合类型并且 ["pending","accepted","rejected"]type string[]

你必须告诉 Typescript 它是 "pending"|"accepted"|"rejected" [] 而不是 string[]

为方便起见,我将创建一个新类型

type State = 'pending' | 'accepted' | 'rejected';

state: State = 'pending'

// we have to tell typescript its type is not string[] but State[] 
state: PropTypes.oneOf(['pending','accepted','rejected'] as State[]).isRequired

here is Example that I have created for you.