You need to enable JavaScript to run this app. 如何编写返回类型可根据入参对象值自动推断的泛型TypeScript函数
优惠活动
大模型
产品
解决方案
定价
更多

如何编写返回类型可根据入参对象值自动推断的泛型TypeScript函数

TypeScript 类型安全的分类映射复用实现

原实现的问题定位

  • 原代码中泛型约束T extends any等同于无约束,容易让TS把入参的异质值宽化为联合类型,失去严格的类型校验能力
  • 箭头函数上的泛型标记没有做JSX兼容处理,在.tsx文件场景下会被解析器识别为JSX标签语法,直接编译报错,也就是原代码“看起来不生效”的核心原因
  • 没有建立从入参值类型到返回值类型的全链路推导,需要手动传入泛型参数才能生效,使用体验差。

正确的通用实现

首先保留原有的基础类型定义:

type IntentColorCategory = 'brand' | 'neutral' | 'semantic'
type IntentColor = 'primary' | 'secondary' | 'neutral' | 'error' | 'success'

实现工厂函数:

const getByIntentColorCategory = <T,>(
  colorMap: Record<IntentColorCategory, T>
): (intent: IntentColor) => T => {
  const { brand, neutral, semantic } = colorMap
  switch (intent) {
    case 'primary':
    case 'secondary':
      return brand;
    case 'neutral':
      return neutral;
    case 'error':
    case 'success':
    default:
      return semantic;
  }
}

注:泛型标记<T,>后的逗号是为了兼容.tsx文件的语法解析,避免被误识别为JSX标签,是React+TS场景下写泛型箭头函数的通用写法。

实现效果

  • 全链路自动类型推导,不需要手动传入泛型参数:TS会自动识别传入对象的值类型T,同时严格校验入参必须包含brand/neutral/semantic三个必填键,且每个键的类型均匹配T
  • 返回的高阶函数的返回值类型与T完全一致,没有类型宽化
    // 自动推导T为number,入参必须传入全number值的对象,返回函数调用后返回number
    const getNumberMappedColor = getByIntentColorCategory({ brand: 1, semantic: 2, neutral: 3 })
    const numberResult = getNumberMappedColor('primary') // 类型严格为number
    
    // 自动推导T为string,入参必须传入全string值的对象,返回函数调用后返回string
    const getStringMappedColor = getByIntentColorCategory({ brand: 'a', semantic: 'b', neutral: 'c' })
    const stringResult = getStringMappedColor('error') // 类型严格为string
    

可选的严格同类型校验版本

如果需要强制约束传入对象的三个值类型完全一致(不允许推导为联合类型),可以给泛型增加校验逻辑:

const getByIntentColorStrict = <TBrand, TNeutral, TSemantic>(
  colorMap: {
    brand: TBrand,
    neutral: TNeutral,
    semantic: TSemantic
  } & ([TBrand, TNeutral, TSemantic] extends [TNeutral, TSemantic, TBrand] 
    ? unknown 
    : {
        __error: 'All color category values must use the exact same type'
      }
  )
): (intent: IntentColor) => TBrand => {
  const { brand, neutral, semantic } = colorMap
  switch (intent) {
    case 'primary':
    case 'secondary':
      return brand;
    case 'neutral':
      return neutral;
    case 'error':
    case 'success':
    default:
      return semantic;
  }
}

这个版本会在传入异质值时直接抛出类型提示,要求三个键的值类型完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.01 18:36:03