使用TypeScript索引访问语法时如何保留方法的泛型参数?
保留泛型特性提取方法类型
问题重现
直接从对象类型中索引提取泛型方法时,TypeScript会丢失其泛型参数特性,导致无法像原方法一样传入泛型参数:
type Foo = { bar<T>(arg: T): T } type Bar = Foo['bar'] type Test = Bar<string> // 错误:Type 'Bar' is not generic.(2315)
解决方案
通过自定义泛型工具类型,我们可以将提取到的方法类型重新包装为保留泛型参数的函数类型:
type Foo = { bar<T>(arg: T): T } // 泛型工具类型:恢复方法的泛型特性 type GetGenericMethod<T> = T extends <U>(...args: infer P) => infer R ? <U>(...args: P) => R : never; type Bar = GetGenericMethod<Foo['bar']>; type Test = Bar<string>; // 类型为 (arg: string) => string,正常工作
工作原理
GetGenericMethod 利用条件类型的推断能力:
- 检查输入类型是否匹配泛型函数的结构
<U>(...args: infer P) => infer R - 若匹配,则返回一个结构完全一致的泛型函数类型,从而保留原方法的泛型参数能力
简化场景写法
如果仅针对单个特定方法,也可以直接手动声明泛型函数类型,省去工具类型:
type Foo = { bar<T>(arg: T): T } type Bar = <T>(arg: T) => T; type Test = Bar<string>; // 正常工作
这种方式适合简单场景,但工具类型的写法更通用,尤其当需要处理多个不同泛型方法时。
内容的提问来源于stack exchange,提问作者astatochek
相关产品推荐
相关产品推荐

