How to use Type aliases In Typescript

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"
}
]
}

How to Implement Recursive Generics in TypeScript ?

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:

Table of Content

  • Using Interfaces
  • Using Type aliases
  • Using Classes

Similar Reads

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

Using Type aliases

...

Using Classes

This TypeScript code defines a type named RecursiveTreeNode, representing a tree node with a value of type T and an optional array of child nodes of the same type....

Contact Us