簡體   English   中英

有沒有辦法在 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" "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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM