Bird
Raised Fist0
Typescriptprogramming~10 mins

Recursive generic types in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Recursive generic types
Define generic type T
↓
Type refers to itself with T
↓
Type expands recursively
↓
Base case stops recursion
↓
Type fully resolved
A recursive generic type is a type that refers to itself with a generic parameter, expanding until a base case stops the recursion.
Execution Sample
Typescript
type NestedArray<T> = T | NestedArray<T>[];

const example: NestedArray<number> = [1, [2, [3, 4], 5], 6];
Defines a recursive generic type NestedArray that can be a value of type T or an array of NestedArray<T>.
Execution Table
StepActionType ExpressionEvaluationResulting Type
1Define NestedArray<T>T | NestedArray<T>[]Type refers to itselfRecursive type definition
2Instantiate NestedArray<number>number | NestedArray<number>[]Expands to number or array of NestedArray<number>Recursive expansion begins
3Evaluate example value[1, [2, [3, 4], 5], 6]Check each element matches NestedArray<number>Valid nested arrays and numbers
4Check base casenumberPrimitive type, recursion stops hereBase case reached
5Full type resolvedNestedArray<number>Nested arrays of numbers or numbersType accepted
💡 Recursion stops when the type reaches the base case (primitive type number).
Variable Tracker
VariableStartAfter Step 2After Step 3Final
TGeneric placeholdernumbernumbernumber
NestedArray<T>T | NestedArray<T>[]number | NestedArray<number>[]number | NestedArray<number>[]number | NestedArray<number>[]
exampleundefinedundefined[1, [2, [3, 4], 5], 6][1, [2, [3, 4], 5], 6]
Key Moments - 3 Insights
Why doesn't the recursive type cause infinite expansion?
Because the recursion stops at the base case when the type is the primitive type number, as shown in step 4 of the execution table.
How does TypeScript know when to stop expanding the recursive generic?
TypeScript stops expanding when it reaches a non-recursive type like number, which acts as the base case (step 4).
Can the recursive generic type hold both single values and arrays?
Yes, the type is defined as T or an array of NestedArray<T>, so it can hold single values or nested arrays, as shown in the example value in step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the type of NestedArray<number> after step 2?
Anumber | NestedArray<number>[]
Bnumber[]
CNestedArray<number>
Dnumber
💡 Hint
Check the 'Resulting Type' column at step 2 in the execution table.
At which step does the recursion stop expanding the type?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look for the step where the base case 'number' is reached in the execution table.
If we changed T to string, how would the variable tracker change after step 2?
AT would be string[], NestedArray<T> would be string[] | NestedArray<string[]>[]
BT would be number, NestedArray<T> would be number | NestedArray<number>[]
CT would be string, NestedArray<T> would be string | NestedArray<string>[]
DNo change
💡 Hint
Refer to the variable tracker row for T and NestedArray after step 2.
Concept Snapshot
Recursive generic types allow a type to refer to itself with a generic parameter.
Syntax example: type NestedArray<T> = T | NestedArray<T>[];
This defines a type that can be a value of T or an array of itself.
Recursion stops at a base case type (like number or string).
Useful for nested data structures like trees or nested arrays.
Full Transcript
This visual execution trace shows how recursive generic types work in TypeScript. We start by defining a generic type NestedArray<T> that can be either a value of type T or an array of NestedArray<T>. When we instantiate it with number, the type expands recursively to allow nested arrays of numbers. The recursion stops when the type reaches the base case, which is the primitive type number. The example value demonstrates valid nested arrays and numbers matching the type. Variable tracking shows how the generic placeholder T is replaced by number and how the example variable holds the nested array structure. Key moments clarify why recursion stops and how the type can hold both single values and arrays. The quizzes test understanding of type expansion, recursion stopping point, and how changing T affects the type. The snapshot summarizes the concept with syntax and behavior. This helps beginners see step-by-step how recursive generic types expand and resolve.

Practice

(1/5)
1. What is the main purpose of using recursive generic types in TypeScript?
easy
A. To create simple flat types without any nesting
B. To automatically generate UI components
C. To enforce runtime type checking
D. To define types that refer to themselves for nested or hierarchical data

Solution

  1. Step 1: Understand recursive generic types

    Recursive generic types allow a type to refer to itself, which helps model nested or hierarchical data structures like trees or linked lists.
  2. Step 2: Compare options

    Options A, C, and D do not describe recursive generics correctly. Only To define types that refer to themselves for nested or hierarchical data correctly states their purpose.
  3. Final Answer:

    To define types that refer to themselves for nested or hierarchical data -> Option D
  4. Quick Check:

    Recursive generics = self-referential types [OK]
Hint: Recursive generics model nested data by referring to themselves [OK]
Common Mistakes:
  • Thinking recursive generics are for runtime checks
  • Confusing recursive generics with simple generics
  • Assuming recursive generics flatten data
2. Which of the following is the correct syntax to define a recursive generic type for a nested object with children of the same type?
easy
A. type Node<T> = { value: T; children: Node[] };
B. type Node<T> = { value: T; children?: Node<T>[] };
C. type Node<T> = { value: T; children: Node<T> };
D. type Node<T> = { value: T; children: T[] };

Solution

  1. Step 1: Analyze recursive generic syntax

    The type should refer to itself with the generic parameter and allow children to be an array of the same type or optional to avoid infinite recursion.
  2. Step 2: Check each option

    type Node<T> = { value: T; children?: Node<T>[] }; correctly defines children as optional array of Node<T>. type Node<T> = { value: T; children: Node[] }; misses generic parameter. type Node<T> = { value: T; children: Node<T> }; makes children a single Node, not array. type Node<T> = { value: T; children: T[] }; uses T[] which is incorrect.
  3. Final Answer:

    type Node<T> = { value: T; children?: Node<T>[] }; -> Option B
  4. Quick Check:

    Recursive generic with optional children array = type Node<T> = { value: T; children?: Node<T>[] }; [OK]
Hint: Use optional array of same generic type for recursive children [OK]
Common Mistakes:
  • Omitting generic parameter in recursive reference
  • Making children non-array when it should be array
  • Not making children optional causing infinite recursion
3. Given the following TypeScript code, what is the type of tree.children[0].children[0].value?
type TreeNode<T> = { value: T; children?: TreeNode<T>[] };
const tree: TreeNode<string> = {
  value: "root",
  children: [
    { value: "child1", children: [{ value: "grandchild1" }] },
    { value: "child2" }
  ]
};
medium
A. string
B. TreeNode<string>
C. string | undefined
D. TreeNode<string> | undefined

Solution

  1. Step 1: Understand the type definition

    TreeNode<T> has a value of type T. Here, T is string.
  2. Step 2: Trace the property access

    tree.children[0].children[0].value accesses the value of a nested node, which is a string as per the generic type.
  3. Final Answer:

    string -> Option A
  4. Quick Check:

    Nested node value type = string [OK]
Hint: Generic type T defines value type at all levels [OK]
Common Mistakes:
  • Confusing node type with value type
  • Assuming children or value can be undefined here
  • Mixing up generic parameter with node type
4. Identify the error in this recursive generic type definition:
type ListNode<T> = {
  value: T;
  next: ListNode<T>;
};
medium
A. 'value' should be optional
B. Generic parameter T is not used correctly
C. Missing optional property for 'next' causing infinite recursion
D. TypeScript does not support recursive types

Solution

  1. Step 1: Analyze the recursive type definition

    The next property refers to ListNode<T> without being optional, so it requires an infinite chain.
  2. Step 2: Identify the fix

    Making next optional (next?: ListNode<T>) provides a base case to stop recursion.
  3. Final Answer:

    Missing optional property for 'next' causing infinite recursion -> Option C
  4. Quick Check:

    Recursive types need optional base case [OK]
Hint: Make recursive property optional to avoid infinite recursion [OK]
Common Mistakes:
  • Forgetting to add '?' to recursive property
  • Thinking TypeScript disallows recursive types
  • Making unrelated properties optional
5. You want to create a recursive generic type NestedArray<T> that represents an array of elements of type T or arrays of NestedArray<T> (nested arrays). Which of the following definitions correctly models this?
hard
A. type NestedArray<T> = Array;
B. type NestedArray<T> = T | NestedArray<T>[];
C. type NestedArray<T> = Array<T> | NestedArray<T>;
D. type NestedArray<T> = T[] | NestedArray<T>;

Solution

  1. Step 1: Understand the nested array structure

    A nested array can be an array of elements of type T or arrays of nested arrays recursively.
  2. Step 2: Evaluate each option

    type NestedArray<T> = Array; correctly defines NestedArray<T> as an array whose elements are either T or NestedArray<T>. type NestedArray<T> = T | NestedArray<T>[]; is incorrect because it allows a single element T without array wrapper. Options C and D misuse union and array placement.
  3. Final Answer:

    type NestedArray<T> = Array<T | NestedArray<T>>; -> Option A
  4. Quick Check:

    Nested arrays = arrays of T or nested arrays [OK]
Hint: Use array of union of T or NestedArray<T> for nested arrays [OK]
Common Mistakes:
  • Allowing T alone without array wrapper
  • Incorrect union placement outside array
  • Confusing recursive generic with simple union
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard