[英]Is there a way to recursively unwrap a function type in TypeScript?
假设我们有以下类型I
:
type I = () => () => () => "a" | "b" | "c";
有没有办法创建一个通用类型Unwrap
使得Unwrap<I>
评估为"a" | "b" | "c"
"a" | "b" | "c"
"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;
任何帮助将不胜感激。 谢谢!
好吧,这是在 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";
如上面的评论中所列, Unwrap
类型适用于 TypeScript 4.1(即将发布)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.