TypeScript无法从函数参数推断泛型类型参数的正确标注方案
解决TypeScript集合处理器的类型推断问题
问题根源在于CollectionGetter和collectionProcessor都没有绑定泛型类型参数,导致TypeScript无法追踪具体的元素类型,只能默认推断为any。以下是无需显式指定泛型参数的正确类型标注方式:
type Collection<T = any> = T[] // 将CollectionGetter改为泛型类型,关联集合的元素类型T type CollectionGetter<T> = () => Collection<T> // 让collectionProcessor成为泛型函数,从传入的getter自动推断T的类型 function collectionProcessor<T>(getter: CollectionGetter<T>) { const res = getter(); // some processing... return res; } // --- interface Item { id: number; } const myGetter = () => { return [ { id: 1 }, { id: 2 }, { id: 3 } ] as Collection<Item> } const result = collectionProcessor(myGetter); // 此时result的类型为Collection<Item>,符合预期 console.log(result);
关键修改说明:
- 泛型化
CollectionGetter:把原本无泛型的CollectionGetter改成CollectionGetter<T>,明确它返回的是对应元素类型T的集合,让每个getter都能携带自己的类型信息。 - 泛型化
collectionProcessor:将函数定义为collectionProcessor<T>,参数类型指定为CollectionGetter<T>,TypeScript会自动从传入的myGetter中推断出T是Item,进而让返回值类型自动匹配为Collection<Item>。 - 这种方式完全依赖类型推断,不需要手动指定泛型参数,适配你提到的“从更高抽象层级传递参数”的场景。
内容的提问来源于stack exchange,提问作者ZDV
相关产品推荐
相关产品推荐

