BeginnerCoder

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.

Want it another way?
Task

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.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with TypeScript Foundations

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.