TypeScript 进阶必修课:解锁强大的内置工具类型(二)

核心工具类型(二)

1. Exclude<T, U>: 排除联合类型成员

  • 作用: 从联合类型 T 中排除所有可分配给 U 的成员。

  • 示例:

    typescript 复制代码
    type AllPossibleId = number | string | boolean | undefined;
    
    // 我只想要非数字的 ID 类型
    type NonNumericId = Exclude<AllPossibleId, number>;
    // 结果是:type NonNumericId = string | boolean | undefined;
    
    // 排除 null 和 undefined
    type ValidStatus = Exclude<"active" | "inactive" | null | undefined, null | undefined>;
    // 结果是:type ValidStatus = "active" | "inactive";

2. Extract<T, U>: 提取联合类型成员

  • 作用: 从联合类型 T 中提取所有可分配给 U 的成员。

  • 示例:

    typescript 复制代码
    type AllPossibleValue = string | number | boolean | object;
    
    // 我只想要可以被序列化为 JSON 的原始类型
    type JsonPrimitive = Extract<AllPossibleValue, string | number | boolean>;
    // 结果是:type JsonPrimitive = string | number | boolean;

3. NonNullable<T>: 移除 nullundefined

  • 作用: 从类型 T 中排除 nullundefined

  • 示例:

    typescript 复制代码
    type MaybeString = string | null | undefined;
    
    // 确定其不为空后,可以获取其非空类型
    type GuaranteedString = NonNullable<MaybeString>;
    // 结果是:type GuaranteedString = string;
    
    function processString(text: GuaranteedString) {
        console.log(text.length); // ✅ 不会报错,因为 text 保证不是 null 或 undefined
    }
    
    const myText: MaybeString = "Hello";
    if (myText !== null && myText !== undefined) {
        processString(myText); // myText 在这里被收窄为 string
    }

4. ReturnType<T>: 获取函数返回类型

  • 作用: 获取函数类型 T 的返回类型。

  • 示例:

    typescript 复制代码
    function getUserData(id: number, name: string) {
        return { id, name, isAdmin: id === 1 };
    }
    
    // 获取 getUserData 函数的返回类型
    type UserData = ReturnType<typeof getUserData>;
    /* 等同于:
    type UserData = {
        id: number;
        name: string;
        isAdmin: boolean;
    }
    */
    
    const currentUser: UserData = {
        id: 5,
        name: 'Sarah',
        isAdmin: false,
    };

5. Parameters<T>: 获取函数参数类型

  • 作用: 获取函数类型 T 的参数类型,以元组的形式。

  • 示例:

    typescript 复制代码
    function greet(firstName: string, lastName?: string): string {
        return `Hello, ${firstName} ${lastName || ""}`;
    }
    
    // 获取 greet 函数的参数类型元组
    type GreetParams = Parameters<typeof greet>;
    // 结果是:type GreetParams = [firstName: string, lastName?: string | undefined];
    
    
    function callGreet(...args: GreetParams) {
         // 可以在这里对参数进行一些处理
         return greet(...args);
    }
    
    console.log(callGreet("John", "Doe")); // "Hello, John Doe"
    console.log(callGreet("Jane")); // "Hello, Jane "

总结

如果你喜欢本教程,记得点赞+收藏!关注我获取更多JavaScript/TypeScript开发干货

相关推荐
孟陬14 小时前
从 Claude Code 187 种说“正在处理”的方式看一流公司的用户体验
前端·claude·bun
一楼的猫14 小时前
从工具链视角对比:番茄作家助手 vs 第三方写作辅助方案
java·服务器·开发语言·前端·学习·chatgpt·ai写作
掘金一周14 小时前
想换一辆电车,JYM有什么推荐 | 沸点周刊 5.21
前端·人工智能·后端
Nian.Baikal14 小时前
Cesium 3D Tiles 加载与优化实战
前端·cesium
KaMeidebaby15 小时前
卡梅德生物技术快报|噬菌体肽库展示技术构建 Mhp168‑Hsp70 定向随机肽库:流程、质控与数据结果
前端·数据库·其他·百度·新浪微博
lchcy15 小时前
前端实现单点登录(SSO登录)
前端
卷帘依旧15 小时前
SPA下的路由模式详解
前端
环信16 小时前
2026年开发者选择即时通讯厂商应注意的几点
前端
卷帘依旧16 小时前
Generator 全面解析 + async/await 深度对比
前端·javascript
weixin_4713830316 小时前
统一缩放单位基础(px、em、rem)
开发语言·javascript·ecmascript