核心工具类型(二)
1. Exclude<T, U>
: 排除联合类型成员
-
作用: 从联合类型
T
中排除所有可分配给U
的成员。 -
示例:
typescripttype 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
的成员。 -
示例:
typescripttype AllPossibleValue = string | number | boolean | object; // 我只想要可以被序列化为 JSON 的原始类型 type JsonPrimitive = Extract<AllPossibleValue, string | number | boolean>; // 结果是:type JsonPrimitive = string | number | boolean;
3. NonNullable<T>
: 移除 null
和 undefined
-
作用: 从类型
T
中排除null
和undefined
。 -
示例:
typescripttype 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
的返回类型。 -
示例:
typescriptfunction 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
的参数类型,以元组的形式。 -
示例:
typescriptfunction 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开发干货