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

TypeScript中如何将数组元素类型转为属性名与方法对应的对象类型

解决方案

要将ELE联合类型转换为指定的对象类型,核心是利用TypeScript的映射类型重映射语法(TypeScript 4.1及以上版本支持),遍历联合类型中的每个成员,提取key作为属性名、fn作为属性类型。

完整代码示例

// 你原有的ArrayElement类型
type ArrayElement<ArrayType extends readonly unknown[]> =
  ArrayType extends readonly (infer ElementType)[] ? ElementType : never;

// 对应你提供的结构定义只读数组
const KeyToVal = [
  { key: 'setTitle', fn: () => 123 },
  { key: 'getName', fn: (name: '123') => name }
] as const;

type ELE = ArrayElement<typeof KeyToVal>;

// 实现类型转换的核心工具类型
type ConvertToResult<T> = {
  [K in T as K['key']]: K['fn']
};

// 最终得到目标类型
type Result = ConvertToResult<ELE>;

原理说明

  • ConvertToResult<T> 是映射类型,K in T会遍历联合类型T的每个成员;
  • as K['key'] 是重映射语法,将联合成员的key属性值作为新对象的属性名;
  • 属性值直接取对应成员的fn属性类型,生成目标Result结构。

最终Result类型与需求完全匹配:

type Result = {
  setTitle: () => number;
  getName: (name: '123') => "123";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:57:24