I have the following code:
type Document = [number | string | Array<Document>]
TypeScript complains with the following error:
test.ts(7,6): error TS2456: Type alias 'Document' circularly references itself.
Clearly circular references are not allowed. However, I still need this kind of structure. What would be a workaround for this?
The creator of TypeScript explains how to create recursive types here: https://github.com/Microsoft/TypeScript/issues/3496#issuecomment-128553540
The workaround for the circular reference is to use
extends Array
. In your case this would lead to this solution:We already have good answers, but I think we can get closer to what you wanted in the first place:
You may try something like this:
Compared to NPE's answer, you don't need wrapper objects around strings and numbers.
If you want a single number or string to be a valid document (which is not what you asked, but what NPE's answer implies), you may try this:
Update:
Using an interface with index signature instead of an array has the disadvantage of losing type information. Typescript won't let you call array methods like find, map or forEach. Example:
This can be solved by changing the definition of DocumentArray:
Building on what NPE said, types cannot recursively point to themselves, you could unroll this type to whatever level of depth you considered sufficient, e.g.:
Not pretty, but removes the need for an interface or class with a property value.
Here is one way to do it:
Types that reference themselves are known as "recursive types" and are discussed in section 3.11.8 of the language spec. The following excerpt explains why your attempt does not compile:
Your original example uses neither a class nor an interface; it uses a type alias.