Recursive Type Aliases

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.

Syntax:

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

Example: Defining a tree using a recursive type alias for a tree structure where each node can have an arbitrary number of children. We create a simple tree with a root node, two child nodes, and one grandchild node to demonstrate the recursive structure.

Javascript




type TreeNode = {
  value: string,
  children?: TreeNode[],
};
 
const tree: TreeNode = {
  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" }
] }

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

...