我在 TypeScript 中遇到循环默认问题,我不知道如何解决

问题描述 投票:0回答:1

我想通过以下方式定义类型:

export type SequenceNode<
  T extends ComponentSequenceNode = ComponentSequenceNode,
  U extends ContainerSequenceNode = ContainerSequenceNode
> = T | U;

export interface ComponentSequenceNode<T extends SequenceNode = SequenceNode> {
  id: string;
  node: "sequence";
  sequence: "component";
  next: T[];
}

export interface ContainerSequenceNode<T extends SequenceNode = SequenceNode> {
  id: string;
  node: "sequence";
  sequence: "container";
  next: T[];
  into: T[];
}

但是,我收到一条消息,说我对这些类型有循环默认设置。

我想使用泛型并使用此结构来定义类型,但我不知道如何实现它。

javascript typescript interface circular-dependency
1个回答
0
投票

问题是,这个类型参数定义是递归的,

SequenceNode
的默认类型可能是这样的

SequenceNode<SequenceNode<SequenceNode<..., ...>, SequenceNode<..., ...>>, SequenceNode<SequenceNode<..., ...>, SequenceNode<..., ...>>>

编译器将尝试评估那个永无止境的链。

因此,默认情况下,使用

SequenceNode<any, any>
,以便链条“停止”在那里:

export type SequenceNode<
  T extends ComponentSequenceNode = ComponentSequenceNode,
  U extends ContainerSequenceNode = ContainerSequenceNode
> = T | U;

export interface ComponentSequenceNode<T extends SequenceNode = SequenceNode<any, any>> {
  id: string;
  node: "sequence";
  sequence: "component";
  next: T[];
}

export interface ContainerSequenceNode<T extends SequenceNode = SequenceNode<any, any>> {
  id: string;
  node: "sequence";
  sequence: "container";
  next: T[];
  into: T[];
}

您的代码仍然工作相同,任何

SequenceNode<Something, SomethingElse>
都满足
T extends SequenceNode
类型,但默认情况下它的类型更具体。

这是 TS-Playground 链接:https://tsplay.dev/wXL3Jw

© www.soinside.com 2019 - 2024. All rights reserved.