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

Similar Reads

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....

Recursive Type Aliases

...

Using Recursive Types with Generics

Type aliases can also be recursive in TypeScript. This allows for more flexible and complex type definitions compared to interfaces, as type aliases can involve unions, intersections, and other complex types....

Recursive Types for Function Definitions

...