circular type reference nonsense
why does removing an array nest cause this to be a circular dependency?? shouldn't it be functionally the same thing??
https://www.typescriptlang.org/play?#code/C4TwDgpgBAglC8UDaA6NAhANMtKtQGdgAnASwDsBzAXWoFgAoUSKdBKcgVwFsAjCYkmpQAPsiQxajRs2gBhdqjQARbEpSrCJCjXpNw0Zey58BQ0cjl7pDAPS2ojp85eOAblAgAPEgEMoYL6kxFAA9gBmULzEvgDGANYQwARQ4aEh5KFQxBC+BKHkUABcABSMsQVEUL5FsIoAjGpISI3IrQDkwBBE7bTU2J3dwL3UQA
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
2 Replies
to be more clear about the type definition I'm looking for here, it should accept:
-
[1, [1, 'test']]
- [[1, [1, 'test']], [1, 'test']]
- [[1, [1, 'test']], [[[1, [1, 'test']], [1, 'test']], 'test']]
- [1, [[1, [[[1, [1, 'test']], [[1, [1, 'test']], 'test']], 'test']], 'test']]
and so on
basically it starts off with a base [...number[], [...number[], string]]
but any of the ...number[]
s can be replaced with the entire expression
recursivelyThe error you're seeing is not related to circular dependencies, but rather to TypeScript's structural type system. In TypeScript, two types are considered identical if their structures (i.e., their properties and methods) are identical.
In your code, you have an interface
Foo
that has a property bar
of type Bar[]
. Bar
is an interface that has a property foo
of type Foo
. This creates a circular reference between Foo
and Bar
, because Foo
refers to Bar
and Bar
refers back to Foo
.
When you remove the array from the bar
property in Foo
, TypeScript sees Foo
and Bar
as identical, because their structures are now the same: they both have a single property of the same type. This is why you're getting the error "Type alias 'Foo' circularly references itself."
To fix this, you could make Foo
and Bar
distinct in some way. For example, you could add another property to one of them. This would make their structures different, and TypeScript would no longer consider them to be the same type.
Please note that this explanation is based on the general principles of TypeScript's type system and not on the specific documentation provided.