簡體   English   中英

在沒有過多深度錯誤的情況下迭代 TypeScript 類型級鏈表

[英]Iterate Over TypeScript Type-level Linked List without Excessive Depth Error

** 這是一個關於 TypeScript ^4.1 的問題 **

我有一個遞歸鏈表類型。

interface ListNode {
  value: string;
  next: ListNode | undefined;
}

這是一個類型級實例的示例。

type RootNode = {
  value: "a";
  next: {
    value: "b";
    next: {
      value: "c";
      next: undefined;
    };
  };
};

我想將這種窄鏈表類型展平為以下類型。

type Flattened = [
  {value: "a"},
  {value: "b"},
  {value: "c"},
]

我一直遇到 TS 錯誤 2589(深度過大/可能無限)。

這是我迄今為止采取的兩種方法。

  1. 遞歸元組傳播。
type Flatten<T extends ListNode> = [
  Omit<T, "next">,
  ...(T["next"] extends ListNode
    ? Flatten<T["next"]>
    : [])
]
  1. 模擬具有映射類型的元組。
type Flatten<
  T extends ListNode,
  I extends undefined[] = []
> =
  T["next"] extends ListNode
    ? Record<I["length"], Omit<T, "next">> & Flatten<T["next"], [...I, undefined]>
    : Record<I["length"], Omit<T, "next">>;

我什至嘗試硬編碼增量。

type Increment = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

type Flatten<
  T extends ListNode,
  I extends number = 0
> =
  T["next"] extends ListNode
    ? Record<I, Omit<T, "next">> & Flatten<T["next"], Increment[I]>
    : Record<I, Omit<T, "next">>;

盡管如此,我還是收到了錯誤 2589。

如果有人設計了一種解決方法,我將非常感激聽到它是什么。

謝謝你。

原來只有當輸入鏈表類型是從其他遞歸類型派生時才會發生此錯誤。 上述展平方法按預期工作。

interface ListNode {
  value: string;
  next: ListNode | undefined;
}

type RootNode = {
  value: "a";
  next: {
    value: "b";
    next: {
      value: "c";
      next: undefined;
    };
  };
};

type Flatten<T extends ListNode> = [
  Omit<T, "next">,
  ...(T["next"] extends ListNode
    ? Flatten<T["next"]>
    : [])
]

type Result = Flatten<RootNode>; // [{value: "a"}, {value: "b"}, {value: "c"}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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