解决TypeScript中string类型无法赋值给string enum类型的编译报错
TypeScript字符串枚举赋值兼容问题解决方案
问题描述
现有如下代码:
type ExampleClass = { relevantValue: EXAMPLE_STRING_ENUM; } enum EXAMPLE_STRING_ENUM { HELLO = 'hello', } const exampleArray: ExampleClass[] = []; const mockData = { relevantValue: 'hello' } exampleArray.push(mockData);
运行后出现以下编译报错:
Argument of type '{ relevantValue: string; }' is not assignable to parameter of type 'ExampleClass'. Types of property 'relevantValue' are incompatible.
Type 'string' is not assignable to type 'EXAMPLE_STRING_ENUM'.(2345)
该场景的实际业务背景是:mockData来自后端接口返回,字段值是普通字符串而非枚举类型值,原本预期字符串枚举的取值本身就是string类型,TypeScript可以自动识别兼容。
失败的临时修复方案
尝试将类型改为枚举与字符串的联合类型:
type ExampleClass = { relevantValue: EXAMPLE_STRING_ENUM | string; }
该方案没有解决根本问题,还会引发后续赋值报错,例如下方给React状态赋值的场景:
exampleArray.forEach((e) => { setFoo(e.relevantValue) })
报错内容为:
Argument of type 'string' is not assignable to parameter of type 'SetStateAction<EXAMPLE_STRING_ENUM | undefined>'.(2345)
最终解决方案
这个报错的逻辑是合理的:编译器无法确认外部传入的普通字符串是否匹配枚举的取值范围,我们可以对不确定的取值添加类型断言处理,修改后的代码如下:
const [foo, setFoo] = React.useState<EXAMPLE_STRING_ENUM>(); type ExampleClass = { relevantValue: string; } enum EXAMPLE_STRING_ENUM { HELLO = 'hello', } const exampleArray: ExampleClass[] = []; const mockData: ExampleClass = { relevantValue: 'hello' } exampleArray.forEach((e) => { setFoo(e.relevantValue as EXAMPLE_STRING_ENUM) })
内容的提问来源于stack exchange,提问作者Leviathan
相关产品推荐
相关产品推荐

