Jesper
Jesper

Reputation: 73

Hint outcome of infinitely recursive type

Given the following code:

type Recursive<A> = 
  | A
// We'd like to use `NeedsParsing<Recursive<A>>` here, but recursive types are only possible as "property values" (how are these correcly called?)
  | {
    parse: Recursive<A>;
  }

type NeedsParsing<A> = {
  parse: A;
}

type Parse<T> = T extends NeedsParsing<infer A>
  ? Parse<A>
  : T;

type X = Parse<Recursive<string>>;
//       ~~~~~~~~~~~~~~~~~~~~~~~~ Type instantiation is excessively deep and possibly infinite. (2589)

TS Playground

In practice, X should resolve to string, since the infinitely deep type Recursive<string> can be resolved by the equally infinite recursive type Parse<T>.

However, this is something that TypeScript cannot deal with and errors rightfully with Type instantiation is excessively deep and possibly infinite. (2589).

With a depth limiter, however, the type can be resolved again.

My question is not what the best way to go about my initial problem is. I am typing something that infinitely (ignore call stack) resolves types at runtime, and would like to represent this accurately with types without limiting myself to a certain recursion depth (16 in the above link).

Upvotes: 0

Views: 112

Answers (0)

Related Questions