What are recursive types in TypeScript?
Answer
Recursive types are types that reference themselves in their own definition, allowing you to model arbitrarily nested data structures. TypeScript supports recursive type aliases. Linked list: type ListNode<T> = { value: T; next: ListNode<T> | null };. Tree node: type TreeNode<T> = { value: T; children: TreeNode<T>[] };. JSON value: type JSONValue = string | number | boolean | null | JSONValue[] | { [key: string]: JSONValue }; — this recursive definition correctly models all valid JSON. Nested partial: type DeepPartial<T> = { [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K] }; — makes all nested properties optional. TypeScript handles recursive types gracefully and they are evaluated lazily, preventing infinite loops in the type checker. They are essential for modeling file system structures, DOM trees, ASTs, and deeply nested configuration objects.
Previous
What is the useUnknownInCatchVariables option in TypeScript?
Next
What is the Extract and Exclude difference and when to use each?