Ts Recursive Types
Recursive types are types that reference themselves, which is very useful when dealing with tree structures and nested data.
TypeScript supports recursive type definitions, which can express data structures of infinite depth.
* * *
* * *
## Why Recursive Types Are Needed
In the real world, data structures are often nested.
For example, file systems have folders and subfolders, organizational structures have departments and subdepartments, and JSON data can be infinitely nested.
Recursive types allow us to express this infinitely nested structure and are the foundation for handling tree-like data.
> **Concept:** A recursive type is a type that references itself in its type definition and can express nested structures of arbitrary depth.
* * *
## Tree Structure
The most common application of recursive types is representing tree structures.
## Instance
// Define tree node type, children references itself
interface TreeNode {
id: number;// Node ID
name: string;// Node name
children?: TreeNode[];// Child nodes array, recursive reference
}
// Create tree structure
const fileSystem: TreeNode ={
id:1,
name:"Root Directory",
children:[
{
id:2,
name:"Folder 1",
children:[
{ id:5, name:"FileA.txt"},
{ id:6, name:"FileB.txt"}
]
},
{
id:3,
name:"Folder 2",
children:[
{ id:7, name:"FileC.txt"}
]
},
{
id:4,
name:"File.txt"
}
]
};
// Function to traverse tree
function traverse(node: TreeNode, depth: number =0):void{
const indent =" ".repeat(depth);
console.log(indent +"📁 "+ node.name);
if(node.children){
for(const child of node.children){
traverse(child, depth +1);
}
}
}
traverse(fileSystem);
**Running Result:**
📁 Root Directory 📁 Folder 1 📁 FileA.txt 📁 FileB.txt 📁 Folder 2 📁 FileC.txt 📁 File.txt
> **File System:** Tree structure is a classic application of recursive types and can represent directory trees, organizational structures, and more.
* * *
## Nested List
Recursive types can also represent nested list structures.
## Instance
// Define nested list type
type NestedList= T | NestedList[];
// Define task type
interface Task {
id: number;
title: string;
completed:boolean;
}
// Create nested task list
const tasks: NestedList=[
{ id:1, title:"Project A",completed:false},
[
{ id:2, title:"Subtask 1",completed:true},
{ id:3, title:"Subtask 2",completed:false}
],
{ id:4, title:"Project B",completed:false}
];
// Calculate nested list depth
function getDepth(list: NestedList, depth: number =0): number {
if(Array.isArray(list)){
let maxDepth = depth +1;
for(const item of list){
maxDepth =Math.max(maxDepth, getDepth(item, depth +1));
}
return maxDepth;
}
return depth;
}
console.log("List Depth: "+ getDepth(tasks));
> **Union Type:** Using T | NestedList[] allows handling both single elements and arrays.
* * *
## Deep Readonly Type
Use recursive
YouTip