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.
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.
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;
};
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.
✅ DeepPartial – Extends TypeScript’s Partial
utility to make all nested properties optional.
✅ UnwrapArray – Extracts the inner type of multidimensional arrays.
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.
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 ProfileJoin with Shikhil’s personal invite link.
1
11
0