TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Recursive data structure type alias "circularly references itself" only if used before declaration

Open jeffreymorlan opened this issue 11 years ago • 3 comments

var x: StringTree;

type StringTree = string | StringTreeArray;
interface StringTreeArray extends Array<StringTree> {}

This code gets a "Type alias 'StringTree' circularly references itself." error. I believe it should be allowed per the spec, since the Type Aliases section doesn't say that an interface type depends on its base interfaces.

If I move the variable declaration below the type and interface, then the error goes away, but the language service still reports that x has type any.

jeffreymorlan avatar Feb 05 '15 04:02 jeffreymorlan

This seems like an omission in the spec. An interface type does in fact depend on its base types.

The error goes away because when the type checker reaches the type alias by walking the tree, it doesn't call getDeclaredTypeOfTypeAlias immediately. It only calls it when processing a reference to that type alias. And so the interface declaration breaks the reference cycle first. This feels to me like a bug.

Even in the absence of an error, I'm surprised the language service says it is any and not string | StringTree. I can look into this more.

JsonFreeman avatar Mar 27 '15 00:03 JsonFreeman

I have found two other ways to observe this problem of an interface directly depending on things it references:

  • An interface/class directly depends on the types referenced by its indexers.
  • An interface directly depends on the return type annotation of its call/construct signatures.

JsonFreeman avatar Apr 09 '15 19:04 JsonFreeman

Fixed by #2813

JsonFreeman avatar Apr 17 '15 21:04 JsonFreeman