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"]));
本例需在 固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行
入口文件:examples/9193b1c03aaa5085fe260bdc/core/core.ts
预期结果与验证条件观察提示
- 树按深度缩进列出根/教程两叶/工具一叶/笔记,顺序固定
- 深度 2
- 1 -> 2 -> 3 -> 4 与长度4
- 1.0.0、[3000,8080]、蓝色天空网
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联72章) · 含当前章节或实例 · mbskycom202611a325.zip