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

TypeScript如何约束函数两个入参匹配同一key的关联类型?

这种参数约束完全可以在TypeScript编译层面实现,不需要依赖运行时类型信息,核心是建立枚举值和对应数据类型的映射关系,再通过泛型绑定两个入参的类型关联。

完整实现步骤

  1. 定义枚举到数据结构的映射类型,建立SourceIdentifier和对应数据结构的关联关系:
type SourceDataMap = {
  [SourceIdentifier.A]: DataA
  [SourceIdentifier.B]: DataB
}
  1. (可选)定义枚举到聚合类的映射类型,明确managers的结构,避免隐式类型推导的问题:
type SourceAggregatorMap = {
  [K in SourceIdentifier]: BaseAggregator<SourceDataMap[K]>
}

const managers: SourceAggregatorMap = {
  [SourceIdentifier.A]: new AggregatorA(),
  [SourceIdentifier.B]: new AggregatorB()
}
  1. 改造dispatch函数,通过泛型绑定入参的对应关系:
const dispatch = <T extends SourceIdentifier>(data: SourceDataMap[T], source: T) => {
  // 此处的类型断言是安全的,因为泛型约束已经保证了data和source的匹配关系
  (managers[source] as BaseAggregator<SourceDataMap[T]>).add(data)
}

校验效果

调用时TypeScript会自动根据传入的source值约束data的类型:

// 合法调用,类型校验通过
dispatch({ prop1: 1, prop2: [1, 2] }, SourceIdentifier.A)
dispatch({ prop3: 3, prop4: 4 }, SourceIdentifier.B)

// 错误调用,编译阶段直接抛出类型错误:类型“{ prop3: number; prop4: number; }”的参数不能赋给类型“DataA”的参数
dispatch({ prop3: 3, prop4: 4 }, SourceIdentifier.A)

补充说明

如果需要运行时的鲁棒性,可以额外加对应数据结构的类型守卫判断,但类型层面的约束已经足够覆盖开发阶段的传参错误问题,不会出现类型不匹配的调用进入运行时。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 01:39:03