0
0
Typescriptprogramming~30 mins

Recursive generic types in Typescript - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Recursive Generic Types in TypeScript
📖 Scenario: Imagine you are building a system to represent nested folders and files, like a simple file explorer. Each folder can contain files and other folders inside it.
🎯 Goal: You will create a recursive generic type called TreeNode that can represent this nested structure. Then, you will create an example folder tree using this type and print the names of all files and folders.
📋 What You'll Learn
Create a recursive generic type TreeNode that has a name and optional children which is an array of TreeNode.
Create a variable folderTree using TreeNode to represent a folder with nested files and folders.
Write a function printTree that recursively prints the names of all nodes in the tree.
Call printTree with folderTree and print the output.
💡 Why This Matters
🌍 Real World
Recursive generic types help represent complex nested data like file systems, menus, or organizational charts in a clear and type-safe way.
💼 Career
Understanding recursive types is important for TypeScript developers working on frontend or backend projects that handle hierarchical data structures.
Progress0 / 4 steps
1
Create the recursive generic type TreeNode
Create a recursive generic type called TreeNode with a generic parameter T. It should have a name of type T and an optional children property which is an array of TreeNode<T>.
Typescript
Need a hint?

Think of TreeNode as a box that can hold a name and optionally many smaller boxes of the same type inside it.

2
Create a variable folderTree using TreeNode<string>
Create a variable called folderTree of type TreeNode<string>. It should represent a folder named root with two children: a file named file1.txt and a folder named subfolder which itself contains a file named file2.txt.
Typescript
Need a hint?

Remember that children is an array of TreeNode<string>. Nest the objects accordingly.

3
Write a recursive function printTree to print all names
Write a function called printTree that takes a TreeNode<string> and a depth number (default 0). It should print the node's name with indentation based on depth, then recursively call itself on each child with depth + 1.
Typescript
Need a hint?

Use console.log with indentation. Call printTree inside the loop for children.

4
Call printTree with folderTree and print the output
Call the function printTree with the variable folderTree to print the entire folder structure.
Typescript
Need a hint?

Just call printTree(folderTree) to see the folder structure printed.