有没有办法在 TypeScript 中递归解包函数类型?
Is there a way to recursively unwrap a function type in TypeScript?
假设我们有以下类型 I
:
type I = () => () => () => "a" | "b" | "c";
有没有一种方法可以创建泛型类型 Unwrap
,使 Unwrap<I>
的计算结果为 "a" | "b" | "c"
?
type I = () => () => () => "a" | "b" | "c";
type Result = Unwrap<I>; // "a" | "b" | "c"
以下 (ofc) 产生循环错误:
type Unwrap<
T extends (...args: any[]) => any,
R = ReturnType<T>
> = R extends (...args: any[]) => any
? Unwrap<R>
: R;
如有任何帮助,我们将不胜感激。谢谢!
如上面评论中所列,Unwrap
类型适用于 TypeScript 4.1(soon-to-be 已发布)。
这是在 TypeScript 3 中有效的 hack。实际上并没有那么糟糕。
type I = () => (() => (() => "a" | "b" | "c")) | "e" | (() => "f" | "g");
type Unwrap<T> =
T extends (...args: any[]) => infer R
? { 0: Unwrap<R> }[T extends any ? 0 : never] // Hack to recurse.
: T;
type Result = Unwrap<I>;
// type Result = "e" | "a" | "b" | "c" | "f" | "g";
假设我们有以下类型 I
:
type I = () => () => () => "a" | "b" | "c";
有没有一种方法可以创建泛型类型 Unwrap
,使 Unwrap<I>
的计算结果为 "a" | "b" | "c"
?
type I = () => () => () => "a" | "b" | "c";
type Result = Unwrap<I>; // "a" | "b" | "c"
以下 (ofc) 产生循环错误:
type Unwrap<
T extends (...args: any[]) => any,
R = ReturnType<T>
> = R extends (...args: any[]) => any
? Unwrap<R>
: R;
如有任何帮助,我们将不胜感激。谢谢!
如上面评论中所列,Unwrap
类型适用于 TypeScript 4.1(soon-to-be 已发布)。
这是在 TypeScript 3 中有效的 hack。实际上并没有那么糟糕。
type I = () => (() => (() => "a" | "b" | "c")) | "e" | (() => "f" | "g");
type Unwrap<T> =
T extends (...args: any[]) => infer R
? { 0: Unwrap<R> }[T extends any ? 0 : never] // Hack to recurse.
: T;
type Result = Unwrap<I>;
// type Result = "e" | "a" | "b" | "c" | "f" | "g";