【问题标题】:Type alias circularly references itself类型别名循环引用自身
【发布时间】:2021-07-03 13:32:10
【问题描述】:

为什么会这样:

type Foo = { x: Foo }

但这不是:

type Bar<A> = { x: A }
type Foo = Bar<Foo>
//   ^^^ Type alias 'Foo' circularly references itself

它们不应该是等价的吗?

【问题讨论】:

标签: typescript


【解决方案1】:

根据文档,type alias 可以在属性中引用自己,但不能在声明右侧的任何其他地方引用:

我们也可以让一个类型别名在属性中引用它自己

所以,正如您所说,这是可行的:

type Foo = { x: Foo }

但是,类型别名不可能出现在声明右侧的其他任何地方

但这失败了:

type Foo = Bar<Foo>

【讨论】:

  • 多亏了这一点,我实际上使用接口解决了它...我有type Foo = Record&lt;string, string | Foo&gt;,但我遇到了错误,用interface Foo { [key: string]: string | Foo } 解决了。我仍然认为应该没有区别,但对我来说没关系......
  • “类型别名可以在属性中引用自身,但不能在声明右侧的任何其他地方引用” -- 显然,即 false,因为这有效:type ItemType = string;type CollapsableItemType = (ItemType | CollapsableItemType)[];。它还在您链接到的位置显示该页面已已弃用
  • @SebastianNielsen 谢谢。很高兴知道他们改变了这一点。我会在答案中注明。
【解决方案2】:

好吧,即使你不使用约束,第二个也会失败:

type Bar<A> = { x: string }
type Foo = Bar<Foo> // still fails with the same message

基本上,第二种形式需要是这样的:

type Bar = { x: Foo }
type Foo = Bar;

要等价于第一个。

另外,strictNullChecks 我很确定没有办法初始化这种类型。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2021-01-15
    • 2022-08-03
    • 1970-01-01
    • 2019-09-03
    相关资源
    最近更新 更多