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开发干货

相关推荐
C澒7 小时前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC7 小时前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
0思必得07 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice7 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶3607 小时前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额8 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
WooaiJava9 小时前
AI 智能助手项目面试技术要点总结(前端部分)
javascript·大模型·html5
爱喝白开水a9 小时前
前端AI自动化测试:brower-use调研让大模型帮你做网页交互与测试
前端·人工智能·大模型·prompt·交互·agent·rag
Never_Satisfied9 小时前
在JavaScript / HTML中,关于querySelectorAll方法
开发语言·javascript·html
董世昌419 小时前
深度解析ES6 Set与Map:相同点、核心差异及实战选型
前端·javascript·es6