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

如何从字符串数组自动推导TypeScript响应类型?

如何从字符串数组自动推导TypeScript对象类型?

你可以通过TypeScript的const断言和映射类型实现从输入数组自动推导响应对象的类型,完全不用手动定义每个键。具体步骤如下:

1. 给输入数组添加as const断言

首先要让TypeScript把数组元素识别为具体的字符串字面量类型,而非宽泛的string类型,需要用as const将数组转为只读元组:

const Input1 = ['red', 'blue', 'purple'] as const;
const Input2 = ['blue', 'white'] as const;

2. 提取数组元素的联合类型

通过typeof获取数组的类型,再用[number]取出元组中所有元素的联合类型:

// 得到类型:"red" | "blue" | "purple"
type Input1Keys = typeof Input1[number];
// 得到类型:"blue" | "white"
type Input2Keys = typeof Input2[number];

3. 用映射类型生成响应对象类型

利用TypeScript的映射类型,把上面的联合类型作为对象的键,值统一设为string:

type TGenerated1 = { [K in Input1Keys]: string };
type TGenerated2 = { [K in Input2Keys]: string };

简化写法

也可以把步骤合并成一行,更简洁:

type TGenerated1 = { [K in typeof Input1[number]]: string };
type TGenerated2 = { [K in typeof Input2[number]]: string };

这样生成的TGenerated1和你手动定义的TResponse1完全等价,TGenerated2和TResponse2一致,后续修改输入数组时,类型会自动同步更新,无需手动维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:15:34