TypeScript 递归类型
为树、嵌套列表、链表和JSON结构建立递归类型,分别处理类型复杂度、运行时深度及循环引用。
学完这一章,你能够
- 遍历树和四节点链表
- 说明深只读/深可选的适用范围
- 不把递归形状当有效JSON或无环证明
自引用描述形状,不承诺无限资源
interface TreeNode{id:number;name:string;children?:TreeNode[]}
function traverse(node:TreeNode,depth=0):void{
console.log(" ".repeat(depth)+node.name);
for(const child of node.children??[])traverse(child,depth+1);
}
文件夹和文件可按原根目录、两个文件夹及文件叶节点建树。递归定义能描述任意有限嵌套,但编译器展开、内存与调用栈都有边界;不应写成支持无限深度。类型也未阻止children指回祖先,实际图数据还需循环检测或明确无环条件。
嵌套任务列表的深度约定
type NestedList<T>=T|NestedList<T>[];
interface Task{id:number;title:string;completed:boolean}
function depth<T>(list:NestedList<T>):number{
return Array.isArray(list)?1+Math.max(0,...list.map(item=>depth(item))):0;
}
这里叶节点深度0,空数组深度1;原任务列表外层加一层子任务数组得到深度2。T自身也允许数组时,Array.isArray无法区分“叶数组”与“嵌套容器”,应约定叶类型或使用带kind标签的结构。很大数组不宜展开进Math.max参数,可用循环计算。
深只读与深可选不是冻结或补默认值
type DeepView<T>=T extends (...args:any[])=>any?T:T extends object?{readonly[K in keyof T]:DeepView<T[K]>}:T;
type DeepPatch<T>=T extends (...args:any[])=>any?T:T extends object?{[K in keyof T]?:DeepPatch<T[K]>}:T;
记录User的profile/address和friends可递归得到只读视角;配置的database/credentials与server可递归省略。但这些教学工具需要明确处理函数、数组、Date、Map、类等特例,不是任意对象的完备转换,更不会执行运行时深冻结或自动合并补丁。
链表的值与终止条件
interface ListNode<T>{value:T;next?:ListNode<T>}
function values<T>(start:ListNode<T>):T[]{
const result:T[]=[];let current:ListNode<T>|undefined=start;
while(current){result.push(current.value);current=current.next;}
return result;
}
四个节点1→2→3→4应得到长度4;最后省略next即可终止。在exactOptionalPropertyTypes配置下,next?:Node未必允许显式赋undefined,不能把这两种写法永远视为同一声明。遇到循环链表此迭代也不会自行结束,需要额外约束。
递归JSONValue仍有表达边界
type JSONValue=string|number|boolean|null|JSONValue[]|{[key:string]:JSONValue};
function getValue(input:JSONValue,path:readonly string[]):JSONValue|undefined{
let current:JSONValue|undefined=input;
for(const key of path){
if(typeof current!=="object"||current===null||Array.isArray(current)||!Object.hasOwn(current,key))return undefined;
current=current[key];
}
return current;
}
这保留按对象路径读取version、settings.ports整个数组和metadata.author的目标,不把数组索引路径伪装成已支持。字符串分段数组避免键名本身含点的歧义。number类型仍含NaN/Infinity,递归对象也可能循环,所以该类型不是有效可序列化JSON的完整证明。
完整核心源码与验证目标
展开查看收起
export {};
interface TreeNode{id:number;name:string;children?:TreeNode[]}
const tree:TreeNode={id:1,name:"蓝色天空网",children:[{id:2,name:"教程",children:[{id:5,name:"HTML5"},{id:6,name:"CSS"}]},{id:3,name:"工具",children:[{id:7,name:"JSON"}]},{id:4,name:"学习笔记"}]};
function traverse(node:TreeNode,depth=0):void{console.log(" ".repeat(depth)+node.name);for(const child of node.children??[])traverse(child,depth+1);}
traverse(tree);
type Nested<T>=T|Nested<T>[];
function depth<T>(value:Nested<T>):number{if(!Array.isArray(value))return 0;let max=0;for(const item of value)max=Math.max(max,depth(item));return max+1;}
console.log("深度",depth<number>([1,[2,3],4]));
interface ListNode<T>{value:T;next?:ListNode<T>}
let current:ListNode<number>|undefined={value:1,next:{value:2,next:{value:3,next:{value:4}}}};
const chain:number[]=[];while(current){chain.push(current.value);current=current.next;}
console.log(chain.join(" -> "),chain.length);
type JSONValue=string|number|boolean|null|JSONValue[]|{[key:string]:JSONValue};
const config:JSONValue={version:"1.0.0",settings:{ports:[3000,8080],metadata:{author:"蓝色天空网"}}};
function getValue(input:JSONValue,path:readonly string[]):JSONValue|undefined{let value:JSONValue|undefined=input;for(const key of path){if(typeof value!=="object"||value===null||Array.isArray(value)||!Object.hasOwn(value,key))return undefined;value=value[key];}return value;}
console.log(getValue(config,["version"]),JSON.stringify(getValue(config,["settings","ports"])),getValue(config,["settings","metadata","author"]));
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
- 树按深度缩进列出根/教程两叶/工具一叶/笔记,顺序固定
- 深度 2
- 1 -> 2 -> 3 -> 4 与长度4
- 1.0.0、[3000,8080]、蓝色天空网
本章附件与实例包
常见错误与边界检查
- 递归类型等于无限深度支持
- 类型保证无循环
- DeepReadonly自动冻结
- Nested<T>叶数组歧义
- JSONValue自动排除非有限数与循环
技术规范与官方资料
练习与参考解答
为什么类型允许的children循环会让普通traverse无限运行?
查看参考解答
递归类型只限制引用形状,没有无环不变量。需输入保证树或在运行时维护访问集合并明确如何处理重复引用。