When does a type "circular reference itself"?

Viewed 124

I don't get why "type circular reference itself" sometimes appears and sometimes don't.

Example:

type Item = string;

type CollapsableItem = (Item | CollapsableItem)[];  // Fine

type CollapsableItem = [(Item | CollapsableItem)];  // Fine

type CollapsableItem = [Item, ...(Item | CollapsableItem)];  // TS2456: Type alias 'CollapsableItem' circularly references itself.

The only different in the last one is that I enforced the first element in the array to be Item. Why did that all of sudden cause a circular reference type error?

In general, when does a "type circular references itself" error occur?

1 Answers

Like you mentioned it was just a typo; it should be

type CollapsableItem = [Item, ...(Item | CollapsableItem)[]]

To add context, using the rest operator ... on anything other than an array type is invalid typescript and will result in the following.

type A = [string]
type B = [...(string | A)]

// Error: A rest element type must be an array type.

The reason why the typescript compiler said your code was circular instead of that it used rest on the nonarray type Item is a compiler priority decision, and your declaration was invalid for both of those reasons.

Related