How to Implement Recursive Generics in TypeScript ?
Last Updated :
24 Apr, 2025
In TypeScript, Recursive generics let you use generic types that refer to themselves inside their definition. This is helpful when we are working with nested or hierarchical Data Structures or Algorithms. Using this we can create flexible and reusable code for managing complex Data Structures. There are several approaches to implementing recursive generics in TypeScript which are as follows:
Using Interfaces
In this approach, we define the structure of objects using TypeScript interfaces. Interfaces allow us to specify the shape of an object, including the names and types of its properties.
Syntax:
interface TreeNode<T> {
value: T;
children: TreeNode<T>[];
}
Example: This TypeScript code defines an interface called RecursiveTreeNode<T>, representing a tree node with a value of type T and optional child nodes. Then, it creates a tree structure using this interface, where each node holds a string value. Finally, it logs the tree to the console.
JavaScript
interface RecursiveTreeNode<T> {
value: T;
children?: RecursiveTreeNode<T>[];
}
const tree: RecursiveTreeNode<string> = {
value: "root",
children: [
{
value: "child1",
children: [
{
value: "grandchild1"
}
]
},
{
value: "child2"
}
]
};
console.log(tree);
Output:
[LOG]: {
"value": "root",
"children": [
{
"value": "child1",
"children": [
{
"value": "grandchild1"
}
]
},
{
"value": "child2"
}
]
}
Using Type aliases
This TypeScript code defines a type named RecursiveTreeNode<T>, representing a tree node with a value of type T and an optional array of child nodes of the same type.
It then creates a tree structure using this type, where each node holds a string value. Finally, it logs the tree to the console.
Syntax:
type TreeNode<T> = {
value: T;
children: TreeNode<T>[];
};
Example: TypeScript recursive tree structure with string values: Using type alias to define `RecursiveTreeNode<T>` and creating a hierarchical tree object.
JavaScript
type RecursiveTreeNode<T> = {
value: T;
children?: RecursiveTreeNode<T>[];
};
const tree: RecursiveTreeNode<string> = {
value: "root",
children: [
{
value: "child1",
children: [
{
value: "grandchild1"
}
]
},
{
value: "child2"
}
]
};
console.log(tree);
Output:
[LOG]: {
"value": "root",
"children": [
{
"value": "child1",
"children": [
{
"value": "grandchild1"
}
]
},
{
"value": "child2"
}
]
}
Using Classes
Classes in TypeScript are like blueprints for making objects. They define what properties and functions an object will have. With classes, we can also use generic type parameters, which means we can make a class that works with different types of data. When we make a class recursively generic, it means instances of the class can have properties that are references to other instances of the same class. This lets us build Data Structures like trees or linkedList.
Syntax:
class TreeNode<T> {
value: T;
children: TreeNode<T>[];
constructor(value: T) {
this.value = value;
this.children = [];
}
}
Example: This TypeScript code creates a class representing tree nodes with values and child nodes. It constructs a tree structure with numeric values, establishes parent-child relationships, and logs the root node to the console.
JavaScript
class RecursiveTreeNode<T> {
value: T;
children?: RecursiveTreeNode<T>[];
constructor(value: T) {
this.value = value;
this.children = [];
}
}
const root = new RecursiveTreeNode < number > (1);
const child1 = new RecursiveTreeNode < number > (2);
const child2 = new RecursiveTreeNode < number > (3);
const grandchild = new RecursiveTreeNode < number > (4);
root.children.push(child1);
root.children.push(child2);
child1.children.push(grandchild);
console.log(root);
Output:
[LOG]: RecursiveTreeNode {
value: 1,
children: [
RecursiveTreeNode { value: 2, children: [ [RecursiveTreeNode] ] },
RecursiveTreeNode { value: 3, children: [] }
]
}
Similar Reads
How to implement Inheritance in Typescript ?
Inheritance is a major pillar of object-oriented programming languages and inheritance is used to create a new class from the existing one. The newly created class is known as the Derived class and the class from which the derived class inherited is known as the Base class. An inherited derived clas
2 min read
How to implement sleep function in TypeScript?
In TypeScript, a sleep function delays code execution for a specified duration. It can be implemented using setTimeout with async and await, pausing execution within asynchronous functions to wait for a certain time before continuing, which is useful for managing application timing. Syntaxasync func
2 min read
What is Recursive Generic in TypeScript ?
In TypeScript, a recursive generic is a type that refers to itself within its definition, enabling the creation of data structures or types containing references to the same type within their structure. This capability proves invaluable when dealing with nested or hierarchical data structures like t
4 min read
How to implement Type narrowing in TypeScript?
Type narrowing in TypeScript refers to refining the type of a variable within a conditional block based on runtime checks. This is achieved through techniques like typeof guards, instance checks, or property existence checks, enabling more precise typing and avoiding type errors in subsequent code e
2 min read
Recursive Type Guards In TypeScript
In TypeScript type guards help determine the type of a variable at runtime, they are especially useful when dealing with complex types like unions, discriminated unions or even recursive structures and a recursive type guard is a type guard function that can handle complex nested types, including th
6 min read
Generics Interface in typescript
"A major part of software engineering is building components that not only have well-defined and consistent APIs but are also reusable. " This sentence is in the official documentation we would start with. There are languages that are strong in static typing & others that are weak in dynamic typ
5 min read
How to implement class constants in TypeScript ?
In this article, we will try to understand how to create several class constants (properties with constant values) in TypeScript with the help of certain code examples for better concept understanding as well as clarification. Let us first understand quickly how we may create a class in TypeScript w
3 min read
How to use getters/setters in TypeScript ?
In TypeScript, getters and setters provide controlled access to class properties, enhancing encapsulation and flexibility.Getters allow you to retrieve the value of a property with controlled logic.Setters enable controlled assignment to properties, often including validation or transformations.Java
5 min read
How to Access TypeScript Private Members ?
In this TypeScript article, we will learn how to access the TypeScript private members using different approaches. We can interact with the encapsulated components within the class and access them in the application. There are three different approaches through which we can access TypeScript private
3 min read
How to Create Arrays of Generic Interfaces in TypeScript ?
In TypeScript, managing data structures effectively is crucial for building robust applications. Arrays of generic interfaces provide a powerful mechanism to handle varied data types while maintaining type safety and flexibility. There are various methods for constructing arrays of generic interface
3 min read