问题描述
假设我们具有以下类型的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(即将发布)中工作。
这是可以在TypeScript 3中使用的技巧。实际上并不是那么糟糕。
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";