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

相关推荐
广州华水科技1 天前
单北斗GNSS在桥梁形变监测中的应用与技术进展分析
前端
我讲个笑话你可别哭啊1 天前
鸿蒙ArkTS快速入门
前端·ts·arkts·鸿蒙·方舟开发框架
CherryLee_12101 天前
基于poplar-annotation前端插件封装文本标注组件及使用
前端·文本标注
特立独行的猫a1 天前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
周航宇JoeZhou1 天前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单
代码小库1 天前
【课程作业必备】Web开发技术HTML静态网站模板 - 校园动漫社团主题完整源码
前端·html
VT.馒头1 天前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
珹洺1 天前
Bootstrap-HTML(二)深入探索容器,网格系统和排版
前端·css·bootstrap·html·dubbo
BillKu1 天前
VS Code HTML CSS Support 插件详解
前端·css·html
xixixin_1 天前
【React】中 Body 类限定法:优雅覆盖挂载到 body 的组件样式
前端·javascript·react.js