Recursive Interfaces
Recursive interfaces in TypeScript are used to define an interface that references itself within its definition. This is commonly used for hierarchical data structures, such as trees or linked lists, where each node might contain a reference to another node of the same type.
Syntax:
interface RecursiveInterface {
value: any;
next?: RecursiveInterface;
}
Example: Define a ListNode interface for a linked list, where each node has a value and an optional reference to the next node (next) of the same type. We then create two nodes and link them together.
Javascript
interface ListNode { value: number; next?: ListNode; } const node1: ListNode = { value: 1 }; const node2: ListNode = { value: 2 }; node1.next = node2; console.log(node1); |
Output
[LOG]: {
"value": 1,
"next": {
"value": 2
}
}
What are Recursive Types & Interfaces in TypeScript ?
In TypeScript, recursive types and interfaces are used to define types or interfaces that can refer to themselves in their definition. This is a powerful concept that allows you to describe complex, nested structures with a simple, elegant definition.
Table of Content
- Recursive Interfaces
- Recursive Type Aliases
- Using Recursive Types with Generics
- Recursive Types for Function Definitions