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

如何实现TypeScript函数返回类型推断为传入数组元素为键的对象?

问题描述

我希望函数返回一个以传入数组参数的元素作为键的对象。当传入数组["i","love","potato"]时,希望返回类型被推断为{ i: string; love: string; potato: string }。我的尝试代码如下:

public async getParameters(keys: readonly string[]): Promise<{ [K in typeof keys]: string }> {...}
解决方案

你的代码问题在于:typeof keys是宽泛的readonly string[]类型,K in typeof keys会遍历数组的索引(比如"0"、"1")而非数组元素,最终返回类型会变成{ "0": string; "1": string; ... },不符合预期。

要实现需求,需要用泛型保留数组元素的具体字面量类型,结合T[number]提取数组元素作为键,代码如下:

public async getParameters<const T extends readonly string[]>(keys: T): Promise<{ [K in T[number]]: string }> {
  // 示例实现:根据keys生成对应对象
  const result = {} as { [K in T[number]]: string };
  for (const key of keys) {
    result[key] = "实际获取的字符串值"; // 替换为你的业务逻辑
  }
  return result;
}

关键说明:

  • const T extends readonly string[]:用const泛型参数让TypeScript将传入的字面量数组推断为只读的具体元素类型数组(比如传入["i","love","potato"]时,T会被推断为readonly ["i","love","potato"]),而非宽泛的string[]。
  • T[number]:提取数组T的所有元素类型,即"i" | "love" | "potato"。
  • { [K in T[number]]: string }:遍历这些元素类型作为对象的键,每个键对应的值类型为string,正好匹配你想要的返回类型。

调用示例:

// 返回类型自动推断为 { i: string; love: string; potato: string }
const params = await getParameters(["i","love","potato"]);

内容的提问来源于stack exchange,提问作者Ahmet Yazıcı

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 16:22:42