蓝色天空网mbsky.com · 知识 · 实践 · 创造TypeScript · 本地阅读预览
教程 / 前端开发 / TypeScript

TypeScript 工具类型

分别操作对象属性和联合成员,避免把类型工具当成运行时删字段或数据验证。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

Partial、Required和Readonly各改一个维度

工具变换不会做什么
Partial<T>顶层属性变可选不递归处理嵌套,也不执行对象更新
Required<T>移除可选标记保留readonly;不是同时变可写
Readonly<T>顶层属性变只读不执行Object.freeze或深冻结
typescript · 阅读源码
interface Config { readonly host?: string; port?: number }
const config: Required<Config> = {host:"localhost",port:8080};
// config.host="other"; // 仍是只读,不应修改
const patch: Partial<{name:string;age:number}> = {name:"蓝色天空网"};

可选属性的undefined处理还与exactOptionalPropertyTypes和同态映射规则相关,不能据“必填”推论所有手写undefined联合都会消失。

Pick与Omit只改变可见类型

typescript · 阅读源码
interface User { id:number; name:string; email:string; password:string }
type Basic=Pick<User,"id"|"name">;
type PublicUser=Omit<User,"password">;
function publicView(u:User):PublicUser { return {id:u.id,name:u.name,email:u.email}; }

把完整对象赋给Omit<User,"password">并不会删除原对象password;要对外输出,构造新的白名单对象或做明确运行时转换。Pick选择少数键,Omit排除少数键,Partial<Pick<...>>可描述局部更新。

Record为每个有限键提供值

typescript · 阅读源码
type Role="admin"|"user"|"guest";
const permissions:Record<Role,string[]>={admin:["read","write","delete"],user:["read","write"],guest:["read"]};

有限Role联合通常要求三项齐全;Record<string,V>则描述开放键域,不保证每个运行时字符串真的存在。对任意字典读取需考虑缺项以及noUncheckedIndexedAccess等配置。权限字符串映射本身不是可信授权实现。

Exclude、Extract和NonNullable处理成员集合

typescript · 阅读源码
type OnlyD=Exclude<"a"|"b"|"c"|"d","a"|"b"|"c">;
type Letters=Extract<"a"|"b"|"c"|1|2|3,string>;
type Present=NonNullable<string|number|null|undefined>;

Exclude去掉可赋给目标类型的联合成员,Extract保留这些成员,不是删除对象属性。对普通有限联合可以用集合图帮助理解;涉及any、unknown等特殊类型,不要把集合恒等式机械当成所有类型都成立。现代NonNullable使用交叉等改进实现,不能简单断言它对unknown等永远等同手写Exclude。

ReturnType提取签名,不执行函数

typescript · 阅读源码
function getUser(){return {name:"蓝色天空网",age:25};}
function getConfig(){return {host:"localhost",port:8080};}
type UserResult=ReturnType<typeof getUser>;
type ConfigResult=ReturnType<typeof getConfig>;

typeof在这里取得函数类型,ReturnType只分析返回签名,不调用函数。重载通常依赖最后可见签名;Promise返回得到的仍是Promise,若需要解析后的结果可按版本使用Awaited<ReturnType<...>>。

完整核心源码与验证目标

typescript · 阅读源码
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 工具类型:蓝色天空网核心实验

所需环境:固定版本的TypeScript编译器,启用strict;编译产物在支持ES2022的JavaScript环境中运行

当前源码 SHA256:38cc6a923d25c968c6b171684ba42eba8b550585f1b87c64f51fa8653ebfc4b0

下载本站示例源码
预期结果 · 待实际运行核验
  • 输出局部用户、完整配置和只读基本资料
  • safe公开数据没有password,管理员/访客映射保持原权限目标
  • d a 42及结构匹配getConfig的配置;这些类型工具不生成过滤代码

常见错误与边界

  • Required移除readonly的错误说法
  • Omit自动删除真实密码字段的误解
  • Record<string,V>保证任意键存在
  • 用as断言空对象代替满足必填结构

练习与解答

将完整User直接赋给Omit<User,"password">后JSON.stringify,password会消失吗?

展开参考解答

不会;赋值只改变静态视角。应显式构造{id,name,email}等公开对象,运行时再序列化。

规范与官方依据