How to use Recursive Types with Generics In Typescript
Recursive types and interfaces become even more powerful when combined with generics, enabling the definition of complex, self-referential structures that can contain various types of data.
Syntax:
interface RecursiveGenericInterface<T> {
value: T;
next?: RecursiveGenericInterface<T>;
}
Example: To demonstrate creating a linked list of numbers by using generic interface which allows for the creation of linked list nodes that can hold any type of data.
Javascript
interface GenericListNode<T> { value: T; next?: GenericListNode<T>; } const node1: GenericListNode<number> = { value: 123 }; const node2: GenericListNode<number> = { value: 456, next: node1 }; console.log(node2); |
Output
[LOG]: { "value": 456, "next": { "value": 123 } }
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