What are Recursive Types & Interfaces in TypeScript ? (original) (raw)

Last Updated : 24 Jan, 2025

In TypeScript, recursive types and interfaces are constructs that reference themselves within their definitions, enabling the modeling of complex, nested data structures.

Recursive Interfaces

Recursive interfaces in TypeScript allow an interface to reference itself within its definition, enabling the modeling of hierarchical data structures like trees or linked lists.

**Syntax:

interface RecursiveInterface {
value: any;
next?: RecursiveInterface;
}

JavaScript `

interface ListNode { value: number; next?: ListNode; }

const node1: ListNode = { value: 1 }; const node2: ListNode = { value: 2, next: node1 };

console.log(node2);

`

**Output

{
value: 2,
next: {
value: 1
}
}

Recursive Type Aliases

Type aliases in TypeScript can also be recursive, allowing for flexible and complex type definitions, such as representing tree structures where each node can have multiple children.

**Syntax:

type RecursiveType = {
value: any;
children?: RecursiveType[];
};

JavaScript `

type TreeNode = { value: string, children?: TreeNode[], };

const tree: TreeNode = { value: "root", children: [ { value: "child1", children: [ { value: "grandchild1", }, ], }, { value: "child2", }, ], };

console.log(tree);

`

**Output

{
value: "root",
children: [
{
value: "child1",
children: [
{
value: "grandchild1"
}
]
},
{
value: "child2"
}
]
}

Using Recursive Types with Generics

Combining recursive types with generics allows for the creation of self-referential structures that can handle various data types.

**Syntax:

interface RecursiveGenericInterface {
value: T;
next?: RecursiveGenericInterface;
}

JavaScript `

interface GenericListNode { value: T; next?: GenericListNode; }

const node1: GenericListNode = { value: 123 }; const node2: GenericListNode = { value: 456, next: node1 };

console.log(node2);

`

**Output

{
value: 456,
next: {
value: 123
}
}

Recursive Types for Function Definitions

Recursive types can also define functions that return themselves, useful for creating self-referential algorithms.

**Syntax:

type RecursiveFunction = () => RecursiveFunction | null;

JavaScript `

type RecursiveFunction = () => RecursiveFunction | null;

const recursiveFunction: RecursiveFunction = () => { const stopCondition = true; // Replace with actual logic return stopCondition ? null : recursiveFunction; };

console.log(recursiveFunction());

`

**Output

null