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 }, })
关键调整点
- 调整泛型顺序:将依赖链最上游的
Fetch放在泛型声明首位,接着是依赖Fetch的Store,最后是依赖Store的Select,让TS能按依赖顺序完成类型推导。 - 简化类型定义:移除多余的
StoredValue、FetchedValue等中间泛型变量,直接用ReturnType<>工具类型获取函数返回值类型,减少冗余同时提升推断准确性。
内容的提问来源于stack exchange,提问作者Alexander Farkas
相关产品推荐
相关产品推荐

