Depth-first traversal visits descendants before returning to a sibling. Declare the node shape recursively and decide how to handle empty child lists.
Worked example
type Tree = { label: string; children: Tree[] };
const root: Tree = {
label: "src",
children: [
{ label: "app", children: [{ label: "ui", children: [] }] },
{ label: "lib", children: [] },
],
};
console.log(
(() => {
function labels(t: Tree): string[] {
return [t.label, ...t.children.flatMap(labels)];
}
return labels(root);
})(),
);Result
[ 'src', 'app', 'ui', 'lib' ]Implementation notes
A recursive type does not guarantee an acyclic runtime structure. Graph-like input needs visited-node tracking if cycles are possible.
Try it yourself
Give two branches the same label and inspect the traversal order.
Open the TypeScript example →Editorial date April 29, 2026 · Published December 6, 2026