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

TypeScript多连续可选转换函数的泛型返回值类型定义问题

解决TypeScript连续转换函数的类型推断问题

问题出在泛型声明的顺序上,TypeScript的泛型推断逻辑是按泛型声明的先后顺序进行推导的,你的代码中StoredValue依赖Store的返回值,但StoredValue却被声明在Store之前,导致TS无法先推断出Store的类型,进而StoredValue只能被推断为unknown,最终select的参数类型丢失。

修正后的代码

type Fn<Input = any, Output = any> = (input: Input) => Output

const transform = <
  // 先声明最上游的fetch泛型
  Fetch extends Fn<any, unknown>,
  // store依赖fetch的返回值作为输入
  Store extends Fn<ReturnType<Fetch>, unknown>,
  // select依赖store的返回值作为输入
  Select extends Fn<ReturnType<Store>, unknown>,
>(config: {
    fetch: Fetch,
    store: Store,
    select: Select,
  }) => {
  return {} as {
    fetchedValue: ReturnType<Fetch>,
    storedValue: ReturnType<Store>,
    selectedValue: ReturnType<Select>,
  }
}

const ret = transform({
  fetch: (a: number) => {
    return 'fetchedValue' as const
  },
  store: (b) => {
    return 'storedValue' as const
  },
  select: (input) => {
    // 现在input会被正确推断为"storedValue"类型
    return 'selectedValue' as const
  },
})

关键调整点

  1. 调整泛型顺序:将依赖链最上游的Fetch放在泛型声明首位,接着是依赖Fetch的Store,最后是依赖Store的Select,让TS能按依赖顺序完成类型推导。
  2. 简化类型定义:移除多余的StoredValue、FetchedValue等中间泛型变量,直接用ReturnType<>工具类型获取函数返回值类型,减少冗余同时提升推断准确性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 09:31:16