【发布时间】:2021-06-11 10:28:23
【问题描述】:
假设我有两种类型的泛型函数,它们的返回类型不同。一个有返回类型T,另一个有T[]:
type F1 = <T>(t: T) => T
type F2 = <T>(t: T) => T[]
我想知道如何将这两种类型合并为一种通用类型。我想这样做的方式是让新的泛型类型接受另一个泛型类型作为参数(如 C++ 的template template parameters):
// Caution, Fantasy-TypeScript ahead!
// Accepts generic type R as parameter
// to transform return type of generic function
type F<R> = <T>(t: T) => R<T>
// define F1 and F2 in terms of F
type Id<T> = T
type F1 = F<Id>
type F2 = F<Array>
但是,泛型泛型参数尚不受支持(2021 年 3 月)。请参阅TypeScript Issue 和related SO question 了解更多信息。
TypeScript 中的替代方案是什么?
【问题讨论】:
标签: typescript generics typescript-generics