json - 如何使用 Enum 类型的字段执行 Typesafe JSON?

标签 json typescript enums

我有一些符合我定义的 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/

相关文章:

node.js - tsconfig 编译器选项 "module": "system" not working

javascript - 什么类型应该返回服务器端组件

c - 枚举值疑惑?

c# - JsonSerializer.CreateDefault().Populate(..) 重置我的值

java - Jersey JSON 响应作为 HttpUrlConnector 而不是 JSON

javascript - 从 JSON 编码获取控制台中 undefined object

c# - Unity - 使用枚举属性来检测对象碰撞

javascript - 如何使用 XMLHttpRequest 从 json 生成变量?

typescript - 我如何编写一个返回与参数相同类型的 TypeScript 函数?

c# - 如何从 EnumMember wcf 获取值