我有一些符合我定义的 TypeScript 接口(interface)的 JSON 文件。
在大多数情况下,当导入此类 JSON 文件并将它们分配给类型化变量时,TypeScript 能够自动推断类型签名(参见下面代码中的 behaves exactly as I want
)。但是当类型包括 字符串枚举 ,它不再起作用(见 DOES NOT behave
)。
以下是工作 Minimal, Reproducible Example :
有效.json
{ "id": 3.14159 }
无效.json
{ "id": "3.14159" }
有效枚举.json
{ "color": "red" }
无效枚举.json
{ "color": "chartreuse" }
index.ts
import validJson from './valid.json'
import invalidJson from './invalid.json'
import validJsonEnum from './validEnum.json'
import invalidJsonEnum from './invalidEnum.json'
type ColorType = 'red' | 'blue' | 'yellow'
type IJsonType = {"id": number}
type IJsonTypeWithEnum = {"color": ColorType}
// behaves exactly as I want
const a: IJsonType = validJson // no error
const b: IJsonType = invalidJson // ERROR: Type 'string' is not assignable to type 'number'.
// DOES NOT behave as I want: SHOULD NOT error
const c: IJsonTypeWithEnum = validJsonEnum // ERROR: Type 'string' is not assignable to type 'ColorType'.
// DOES NOT behave as I want: error should be that "chartreuse" is not assignable to type 'ColorType'
const d: IJsonTypeWithEnum = invalidJsonEnum // ERROR: Type 'string' is not assignable to type 'ColorType'.
我可以使用
type IJsonTypeWithEnum = {"color": string}
使错误消失,但这违背了目的。是否有任何解决方法或编译器开关可以使 TypeScript 将 JSON 中的枚举值识别为字符串?还是 JSON 类型推断的 TypeScript 限制?
最佳答案
尝试使用类型断言
const data: IJsonType = jsonData as IJsonType;
关于json - 如何使用 Enum 类型的字段执行 Typesafe JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60292502/