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

如何从数组参数生成类型并在映射函数中作为参数类型使用?

实现数组参数到Record类型的动态映射

要实现这个动态类型推导,核心是利用TypeScript的泛型关联传入的数组元素类型和映射函数的参数类型。具体修改如下:

关键调整步骤

  • 将createConfig定义为泛型函数,通过泛型参数T捕获传入dependencies数组的具体元素类型(T约束为ItemType)。
  • 让MappingFn依赖于泛型T,确保映射函数的dependencies参数是对应T的Record类型。

完整代码示例

enum Item {
  A = 'A',
  B = 'B',
  C = 'C'
}
type ItemType = `${Item}`

// 泛型版本的映射函数类型,与传入的元素类型绑定
type MappingFn<T extends ItemType> = (dependencies: Record<T, any>) => string;

// 泛型createConfig,自动推导数组元素的联合类型
const createConfig = <T extends ItemType>(dependencies: T[], mappingFn: MappingFn<T>) => {
  // 可根据需求添加逻辑,比如构造符合类型的dependencies对象并传入映射函数
  const resolvedDependencies = {} as Record<T, any>;
  return mappingFn(resolvedDependencies);
}

// 调用示例:dependencies自动推导为Record<Item.A | Item.B, any>
createConfig([Item.A, Item.B], (dependencies) => {
  dependencies.A; // 正常访问,无类型错误
  dependencies.B; // 正常访问,无类型错误
  dependencies.C; // 类型错误:Record<Item.A | Item.B, any>不存在属性"C"
  return '';
});

说明

  • 泛型T会自动推导为数组元素的联合类型,比如传入[Item.A, Item.B]时,T就是Item.A | Item.B。
  • Record<T, any>生成的对象类型仅包含T中的键,因此访问未传入的键(如C)会触发TypeScript类型检查错误。
  • 如果需要更严格的类型约束,可将any替换为具体的类型(比如string、number或自定义类型)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 19:25:47