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

TypeScript:为字符串数组转指定键对象的函数添加类型定义

实现TypeScript类型推断的解决方案

这其实可以通过TypeScript的泛型结合映射类型来实现,正好能满足你想要的类型推断需求,我给你拆解一下具体怎么做:

1. 核心类型定义思路

我们需要用泛型捕获输入数组中具体的字符串字面量类型,再通过映射类型把这些字面量转化为返回对象的键。具体来说:

  • 用泛型T extends readonly string[]约束输入参数,让TypeScript保留数组元素的具体字面量(而不是宽泛的string类型)
  • 返回值使用{ [K in T[number]]: true },遍历数组的每个元素类型作为对象的键,值固定为true

2. 完整实现代码

function myFunction<T extends readonly string[]>(keys: T): { [K in T[number]]: true } {
  // 对初始值做类型断言,告诉TS空对象最终会变成目标类型
  return keys.reduce((result, key) => {
    result[key] = true;
    return result;
  }, {} as { [K in T[number]]: true });
}

3. 验证效果

当你调用函数时:

const result = myFunction(['key1', 'key2']);

TypeScript会自动推断result的类型为:

{
  key1: true;
  key2: true;
}

这时候你访问result.key1会得到正确的类型提示,而如果尝试访问result.nonExistentKey,TypeScript会直接抛出类型错误,完美符合你的需求。

补充说明

如果输入的是动态数组(比如const arr = ['a', 'b'] as string[]),TypeScript无法确定具体的键,这时候返回值类型会变成{ [x: string]: true },这是合理的行为——毕竟动态数组的元素类型是宽泛的string,无法做精确推断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 08:57:44