export {};
interface User {id:number;name:string;email:string;password:string}
interface Config {readonly host?:string;port?:number}
const patch:Partial<User>={name:"蓝色天空网"};
const config:Required<Config>={host:"localhost",port:8080};
const view:Readonly<Pick<User,"id"|"name">>={id:1,name:"蓝色天空网"};
const user:User={id:1,name:"蓝色天空网",email:"learn@mbsky.com",password:"demo-only"};
const safe:Omit<User,"password">={id:user.id,name:user.name,email:user.email};
const roles:Record<"admin"|"user"|"guest",string[]>={admin:["read","write","delete"],user:["read","write"],guest:["read"]};
const remaining:Exclude<"a"|"b"|"c"|"d","a"|"b"|"c">="d";
const letter:Extract<"a"|1,string>="a";
const present:NonNullable<string|number|null|undefined>=42;
function getConfig(){return {host:"mbsky.com",port:443};}
const inferred:ReturnType<typeof getConfig>={host:"localhost",port:3000};
console.log(JSON.stringify(patch),JSON.stringify(config),JSON.stringify(view));
console.log(JSON.stringify(safe),roles.admin.join(","),roles.guest.join(","));
console.log(remaining,letter,present,JSON.stringify(inferred));
本例需在 固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行
入口文件:examples/62540c4fb2190df8e9f0250f/core/core.ts
预期结果与验证条件观察提示
- 输出局部用户、完整配置和只读基本资料
- safe公开数据没有password,管理员/访客映射保持原权限目标
- d a 42及结构匹配getConfig的配置;这些类型工具不生成过滤代码
请结合实际环境逐项观察。
附件与关联工程包下载
课程关联工程包(登记关联72章) · 含当前章节或实例 · mbskycom202611a325.zip