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

TypeScript根据传入template枚举值动态推导对应context类型

问题原因

当前SendMailParams的类型定义中,context被直接定义为TemplatesMail[TemplateEnum],这个类型是所有模板对应上下文的联合类型,TypeScript无法根据template字段传入的具体枚举值收窄context的类型范围,因此会提示所有上下文类型的属性,无法做到精准推导。

修复方案

使用可辨识联合类型重构SendMailParams,通过映射类型遍历所有模板枚举值,为每个模板生成匹配的template+context类型组合,再合并为联合类型,即可实现根据传入的template值自动推导对应context的类型。

修正后的完整代码如下:

enum TemplateEnum {
  CANCELLATION_POLICY = 'cancellation-policy',
  ANOTHER_MAIL = 'another-mail'
}

type CancellationPolicyContext = {
  name: string
  cancellationDate: Date
}

type AnotherMailContext = {
  value: number
}

type TemplatesMail = {
  [TemplateEnum.CANCELLATION_POLICY]: CancellationPolicyContext
  [TemplateEnum.ANOTHER_MAIL]: AnotherMailContext
}

// 核心修改:生成模板与上下文一一对应的可辨识联合类型
type SendMailParams = {
  [K in TemplateEnum]: {
    template: K
    context: TemplatesMail[K]
  }
}[TemplateEnum]

const params: SendMailParams = {
  template: TemplateEnum.CANCELLATION_POLICY,
  context: {
    // 此处仅会提示CancellationPolicyContext的name、cancellationDate属性
    name: '张三',
    cancellationDate: new Date()
  }
}

const anotherParams: SendMailParams = {
  template: TemplateEnum.ANOTHER_MAIL,
  context: {
    // 此处仅会提示AnotherMailContext的value属性
    value: 99
  }
}

实现说明

  • 映射类型[K in TemplateEnum]会遍历所有模板枚举值,为每个枚举值K生成独立的类型结构:{template: K, context: TemplatesMail[K]}
  • 最后通过索引取值[TemplateEnum],将所有生成的单模板类型合并为联合类型
  • 传入具体template值时,TypeScript会自动从联合类型中匹配到对应成员,对context做精准类型提示和校验,传入不属于当前模板的context属性会直接抛出类型错误

内容的提问来源于stack exchange,提问作者Max Rogério

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 00:12:53