Skip to the solution
HardFrontend11 min read

What are recursive types?

441 views

The problem

Question presented to candidate: "What are recursive types in TypeScript? Give me a data structure you would model with one, and then a type-level computation that uses recursion. What limits do you run into?"

What a strong answer should cover:

  • A recursive type refers to itself, to describe nesting of unknown depth: Json, trees, linked lists, expression ASTs, including mutual recursion between two types
  • The self-reference must go through a structure (object, array, tuple, generic); a bare type Loop = Loop | string is error TS2456. Type aliases became much more flexible here in TypeScript 3.7
  • Recursive functions walk recursive types, and a discriminated union makes every case checked
  • Recursive conditional types (TypeScript 4.1) compute types: deep array elements, all dotted paths of an object, tuple-length arithmetic
  • The depth limit (error TS2589) and tail-recursive conditional types (TypeScript 4.5), which go about a thousand levels instead of a few dozen; the accumulator pattern

Code / implementation expected: Yes β€” a Json or tree type with a function over it, and one recursive conditional type.

  • recursive-types

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptRecursive data types: Json, trees, lists and mutual recursion
TypeScriptRecursive type-level computation and depth limits

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 76 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextHard

What does the infer keyword do?

Continue