You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从JSON对象数组生成包含所有code的TypeScript类型?

问题:从JSON数组的code字段生成TypeScript类型声明

我的JSON文件结构是对象数组:

[
  {
    "code": "TEST",
    "name": "Testing"
  },
  ...rest
]

我想基于数组中所有对象的code字段创建一个新的TypeScript类型声明。我尝试了以下代码:

const statusTypeCodes = statusTypes.map(t => t.code) as const
type StatusCode = typeof statusTypeCodes[number];

但第一行代码无法正常运行,请问实现该需求的最佳方式是什么?


解决方案

问题出在map方法返回的数组无法被as const断言为只读字面量数组——因为map的返回类型是普通数组,TypeScript无法保留原始code的字面量类型信息。

有两种可靠的实现方式:

方式1:直接从原始数组断言为只读字面量数组

如果你的statusTypes是直接导入的JSON或定义的常量数组,先把它断言为只读字面量数组,再提取code类型:

// 假设statusTypes是导入的JSON或定义的常量
const statusTypes = [
  { code: "TEST", name: "Testing" },
  { code: "ACTIVE", name: "Active" }
] as const;

type StatusCode = typeof statusTypes[number]["code"];
// 最终类型为 "TEST" | "ACTIVE"

方式2:类型工具提取(适配动态加载的JSON)

如果statusTypes是运行时动态加载的(比如通过fetch获取的JSON),可以先定义原始结构类型,再结合静态示例数据推导字面量类型:

// 先定义JSON的基础结构类型
type StatusType = {
  code: string;
  name: string;
};

// 用静态示例数据保留code的字面量信息
const sampleStatusTypes = [
  { code: "TEST", name: "Testing" },
  { code: "ACTIVE", name: "Active" }
] as const;

// 提取示例数据中的code类型
type StatusCode = typeof sampleStatusTypes[number]["code"];

内容的提问来源于stack exchange,提问作者tgreen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 22:42:36