Dev Helpers

TypeScript / Recursive data

Collect labels depth first

Dev Helpers · April 29, 2026

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

Related articles

Reject fractional cent amounts

A numeric type cannot by itself guarantee whole cents. Validate integrality where money enters the typed part of the application.

Infer route names from a registry

A route registry can drive both lookup and allowed route names. Type the keys from the registry so a removed route cannot survive in a separate union.