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

时间:2021-01-06 17:57:06

标签: typescript enums

我明白了:

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] })
                             ~~~~

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

怎么办?

1 个答案:

答案 0 :(得分:1)

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

{ id: number; status: MyStatus; }

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

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