假设我们有以下类型 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;
任何帮助将不胜感激。谢谢!
最佳答案
好吧,这是在 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";
Playground Link
关于typescript - 有没有办法在 TypeScript 中递归解包函数类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63569735/