typescript - 有没有办法在 TypeScript 中递归解包函数类型?

标签 typescript types compiler-errors unwrap inferred-type

假设我们有以下类型 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/

相关文章:

javascript - Angularjs:使用数据动态加载 View 中的指令

C++ 从 LPCTSTR 转换为 const char *

swift - 当子类中有覆盖函数时如何转换为父类(super class)

python-3.x - 当执行下面的代码时,我收到消息错误str连接

javascript - 对象中的 typescript 符号

javascript - 需要一种设计模式来仅获取跨类通用的特定功能

typescript - 何时在 typescript Angular 2 中使用 @Optional() 和三元运算符?

java - 没有明确声明泛型类型的赋值如何被滥用?

java - Java错误-无法在Maven项目中解析符号

generics - 向闭包添加显式返回会导致编译器错误: A compiler bug?