Recursive aliases
Concept and syntax
A recursive alias can describe a finite runtime tree with recursively typed child nodes. The type refers to itself but does not allocate an infinite object. Each runtime tree needs a base case such as an empty children array.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Tree={value:number;children:Tree[]}; function total(t:Tree):number{return t.value+t.children.reduce((s,c)=>s+total(c),0);}const t:Tree={value:2,children:[{value:3,children:[]}]}; console.log(total(t));Expected output:
5Common mistake
Intentionally invalid; compile separately and do not execute.
type Tree={value:number;children:Tree[]}; function total(t:Tree):number{return t.value+t.children.reduce((s,c)=>s+total(c),0);}const t:Tree={value:2,children:[{value:3}]};Expected diagnostic: TS2741. Every child must satisfy the same Tree contract, including children.
Practice and recap
Add a second child and compute the total.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Recursive aliases — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Recursive aliases is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Tree={value:number;children:Tree[]}; function total(t:Tree):number{return t.value+t.children.reduce((s,c)=>s+total(c),0);}const t:Tree={value:2,children:[{value:3,children:[]}]}; console.log(total(t));Which diagnostic and explanation match the rejected example under the lesson settings?
type Tree={value:number;children:Tree[]}; function total(t:Tree):number{return t.value+t.children.reduce((s,c)=>s+total(c),0);}const t:Tree={value:2,children:[{value:3}]};What is the leaf representation for the Tree example?