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

如何在TypeScript中从数组推导指定的对象类型?

TypeScript 推导目标类型的方法

要从给定的数组推导出你期望的Result类型,可按以下步骤操作:

1. 锁定数组的字面量类型

给原数组添加as const断言,让TypeScript保留每个元素中name的具体字符串字面量类型,以及method的精确函数类型,避免被宽泛推断为string或通用函数类型:

const Arr = [
  {
    name: 'setTitle',
    method: (title: string) => {
      return title;
    }
  },
  {
    name: 'getName',
    method: () => {
      return 'hello world';
    }
  }
] as const;

2. 定义工具类型推导结果

创建工具类型,通过映射类型遍历数组元素的name作为键,提取对应method的类型:

type ExtractResult<T extends readonly { name: string; method: (...args: any[]) => any }[]> = {
  [K in T[number]['name']]: Extract<T[number], { name: K }>['method']
};

3. 生成目标类型

通过typeof Arr获取数组的类型,传入工具类型即可得到Result:

type Result = ExtractResult<typeof Arr>;

此时Result会被精确推导为:

type Result = {
  setTitle: (title: string) => string;
  getName: () => string
}

内容的提问来源于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:48:17