Lesson 23 — Recursive types
Types that contain themselves
A recursive type refers to itself, which is how you describe trees: a post has replies, and each reply is a post with its own replies. Code for such data is usually recursive too — a function that calls itself for each child until it reaches items with no children.
type Folder = { name: string; children: Folder[] };
function depth(f: Folder): number {
return 1 + Math.max(0, ...f.children.map(depth));
}
Why it matters: comments, menus, file systems and JSON are all trees.
Finish count so it counts the post plus all its replies at every level. Expect 4.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
A quick 3-question quiz on this lesson — instant feedback.
Ready for more? Optional paid resources that pick up where this lesson leaves off.
Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.
Project-based TypeScript Foundations courses if you want a structured paid path after the free lessons. Wait for a sale — prices drop often.
Browse on Udemy →Search Amazon for TypeScript Foundations books — check the publication year so the examples match current versions.
Search Amazon →