如何实现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ı
相关产品推荐
相关产品推荐

