Open In App

How to Implement Recursive Generics in TypeScript ?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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: [] }
]
}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads