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

如何从键数组与值元组动态构建TypeScript对象类型?

如何用const数组和元组动态构建对应对象类型

我有一个带const断言的键数组,以及一个值元组类型:

const keys = ["name", "age", "isAlive"] as const;
type Values = [string, number, boolean];

想要动态生成如下的对象类型:

type DesiredType = {
   name: string;
   age: number;
   isAlive: boolean;
}

我试了下面的代码,但没达到预期效果:

const keys = ["name", "age", "isAlive"] as const;
type Values = [string, number, boolean];

type ObjFromArrays<K extends readonly string[], V extends any[]> = {
  [I in K[number]]: V[number];
};

type DesiredType = ObjFromArrays<typeof keys, Values>;

问题很明显:这个写法只遍历了键数组的元素,但没把键和元组对应索引的值类型绑定起来,最后每个键的类型都是string | number | boolean的联合类型,不是我要的一一对应关系。


正确实现方案

要让键和元组对应位置的值类型精准匹配,需要利用TypeScript的索引重映射特性,同时遍历元组的索引来关联键和值:

const keys = ["name", "age", "isAlive"] as const;
type Values = [string, number, boolean];

type ObjFromTuples<K extends readonly PropertyKey[], V extends any[]> = {
  [I in keyof K as K[I]]: V[I & keyof V];
};

type DesiredType = ObjFromTuples<typeof keys, Values>;

原理说明

  • keyof K会拿到元组的数字索引(比如"0"、"1"、"2")
  • as K[I]把原本的数字索引重映射成对应的键名(比如K["0"]就是"name")
  • V[I & keyof V]确保索引I在值元组V的索引范围内,从而取出对应位置的值类型(比如V["0"]就是string)

这样就能完美生成键与值类型一一对应的目标对象类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:47:10