Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type alias circularly references itself

Tags:

typescript

Why does this work:

type Foo = { x: Foo }

but this doesn't:

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

Shouldn't they be equivalent?

like image 661
Tom Crockett Avatar asked Feb 20 '17 19:02

Tom Crockett


2 Answers

Per the documentation, a type alias can refer to itself in a property, but not anywhere else on the right side of the declaration:

We can also have a type alias refer to itself in a property

So, as you noted, this works:

type Foo = { x: Foo }

However, it’s not possible for a type alias to appear anywhere else on the right side of the declaration

But this fails:

type Foo = Bar<Foo>
like image 170
Seamus Avatar answered Sep 21 '22 20:09

Seamus


Well, the second fails even if you don't use the constraint:

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

Basically, it the 2nd form needs to be this:

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

To be equivalent to the first one.

Also, with strictNullChecks I'm pretty sure that there's no way to initialize such a type.

like image 30
Nitzan Tomer Avatar answered Sep 24 '22 20:09

Nitzan Tomer