类型"字符串"不能分配给类型"MyEnum"?



我得到的是:

error TS2322: Type '{ id: number; status: string; ... }'.
Types of property 'status' are incompatible.
Type 'string' is not assignable to type 'MyStatus'.
157     callMethod({ array: [item] })
~~~~

其中item = { id: 123, status: MyStatus.Pending }枚举,其中MyStatus.Pending == 'Pending'

该怎么办?

枚举值不会被识别为字符串,反之亦然,即使它们的值匹配。您需要设置接口以接受枚举:

{ id: number; status: MyStatus; }

如果你绝对必须使用字符串,你可以使用as来绕过它,但老实说,这通常意味着你违背了TypeScript:的好处

item = { id: 123, status: MyStatus.Pending as string }

最新更新