Shikhil Saxena

May 29, 2025 • 1 min read

Recursive Types in TypeScript – A Deep Dive

TypeScript offers recursive types, allowing developers to define self-referential structures that are crucial for handling trees, linked lists, and deeply nested objects. This article explores how recursive types work and their practical applications.

1️⃣ Understanding Recursive Types

Recursive types are similar to recursive functions—they reference themselves within their definition.

Example:

type JSONValue =

| string

| number

| boolean

| null

| { [key: string]: JSONValue };


This type allows nested JSON structures where objects contain properties that reference the same type.

2️⃣ Recursive Data Structures

Recursive types are commonly used in trees and linked lists.

Binary Tree Example:

type TreeNode<T> = {

value: T;

left: TreeNode<T> | null;

right: TreeNode<T> | null;

};

Linked List Example:

type LinkedList<T> = {

value: T;

next: LinkedList<T> | null;

};

3️⃣ Recursion with Mapped & Conditional Types

Mapped types allow dynamic transformations, while conditional types enable recursive evaluation.

Example:

type Recursive<T> = {

[K in keyof T]: T[K] extends number ? T[K] : Recursive<T[K]>;

};

This ensures nested properties are processed recursively while preserving numeric values.

4️⃣ Practical Use Cases

DeepPartial – Extends TypeScript’s Partial utility to make all nested properties optional.

UnwrapArray – Extracts the inner type of multidimensional arrays.

5️⃣ When to Use Recursive Types (and When to Avoid Them)

While recursive types are powerful, excessive complexity can lead to longer type-checking times or compile-time errors. Use them sparingly and only when necessary.

Final Thoughts

Recursive types are an advanced TypeScript feature that can simplify complex data structures when used correctly.

🔥 Have you used recursive types in your TypeScript projects? Let’s discuss! 🚀

Join Shikhil on Peerlist!

Join amazing folks like Shikhil and thousands of other people in tech.

Create Profile

Join with Shikhil’s personal invite link.

1

11

0