Typescript中的Utility 类型之间的区别

TypeScript 中的 Utility Types(实用工具类型)是一组内置的泛型类型,用于常见的类型转换操作。它们能够帮助我们更灵活地操作和转换类型。

主要的 Utility Types

1. Partial<T>

将类型 T 的所有属性设置为可选:

interface User {
  id: number;
  name: string;
  email: string;
}

type PartialUser = Partial<User>;
// 等价于 { id?: number; name?: string; email?: string; }

2. Required<T>

将类型 T 的所有属性设置为必需:

interface User {
  id?: number;
  name?: string;
}

type RequiredUser = Required<User>;
// 等价于 { id: number; name: string; }

3. Readonly<T>

将类型 T 的所有属性设置为只读:

type ReadonlyUser = Readonly<User>;
// 所有属性变为只读

4. Record<K, T>

构造一个对象类型,其属性键为 K,属性值为 T:

type UserRecord = Record<string, number>;
// { [key: string]: number }

type SpecificRecord = Record<'name' | 'email', string>;
// { name: string; email: string }

5. Pick<T, K>

从类型 T 中选取一组属性 K:

type UserNameOnly = Pick<User, 'name'>;
// { name: string }

6. Omit<T, K>

从类型 T 中排除一组属性 K:

type UserWithoutEmail = Omit<User, 'email'>;
// { id: number; name: string }

7. Exclude<T, U>

从类型 T 中排除可以赋值给 U 的类型:

type T0 = Exclude<"a" | "b" | "c", "a">;
// "b" | "c"

type T1 = Exclude<string | number | (() => void), Function>;
// string | number

8. Extract<T, U>

从类型 T 中提取可以赋值给 U 的类型:

type T0 = Extract<"a" | "b" | "c", "a" | "f">;
// "a"

9. NonNullable<T>

从 T 中排除 null 和 undefined:

type T0 = NonNullable<string | number | undefined>;
// string | number

10. Parameters<T>

获取函数类型的参数类型:

type Fn = (a: string, b: number) => void;
type Params = Parameters<Fn>;
// [string, number]

11. ReturnType<T>

获取函数类型的返回类型:

type FnReturn = ReturnType<() => string>;
// string

12. InstanceType<T>

获取构造函数类型的实例类型:

class C {
  x = 0;
  y = 0;
}

type T0 = InstanceType<typeof C>;
// C

13. ThisParameterType<T> 和 OmitThisParameter<T>

处理函数的 this 参数类型:

function toHex(this: Number) {
  return this.toString(16);
}

type ThisType = ThisParameterType<typeof toHex>;
// Number

type NoThis = OmitThisParameter<typeof toHex>;
// () => string

14. Awaited<T> (TypeScript 4.5+)

递归展开 Promise 类型:

type A = Awaited<Promise<string>>;
// string

type B = Awaited<Promise<Promise<number>>>;
// number

区别和联系

操作对象属性

  • Partial/Required/Readonly: 操作所有属性的可选性、必需性和只读性

  • Pick/Omit: 选择或排除特定属性

  • Record: 创建新的对象类型

操作联合类型

  • Exclude/Extract: 从联合类型中排除或提取特定类型

  • NonNullable: 排除 null 和 undefined

操作函数类型

  • Parameters/ReturnType: 获取函数参数和返回类型

  • ThisParameterType/OmitThisParameter: 处理 this 参数

关系对比

// Partial vs Required (互逆操作)
type User = { id: number; name?: string };
type PartialUser = Partial<User>;        // 所有属性可选
type RequiredUser = Required<User>;      // 所有属性必需

// Pick vs Omit (互补操作)
type Picked = Pick<User, 'id'>;          // { id: number }
type Omitted = Omit<User, 'id'>;         // { name?: string }

// Exclude vs Extract (互补操作)
type Excluded = Exclude<'a' | 'b' | 'c', 'a'>;  // 'b' | 'c'
type Extracted = Extract<'a' | 'b' | 'c', 'a'>; // 'a'

实际应用示例

// 创建可选的更新对象
interface Product {
  id: number;
  name: string;
  price: number;
  category: string;
}

function updateProduct(id: number, updates: Partial<Product>) {
  // 只更新提供的字段
}

// 创建只读的配置对象
const config: Readonly<Record<string, any>> = {
  apiUrl: 'https://api.example.com',
  timeout: 5000
};

// 从函数类型提取有用的信息
async function fetchUser(id: string): Promise<User> {
  // ...
}

type FetchUserParams = Parameters<typeof fetchUser>;  // [string]
type UserPromise = ReturnType<typeof fetchUser>;      // Promise<User>
type UserData = Awaited<ReturnType<typeof fetchUser>>; // User

这些 Utility Types 大大增强了 TypeScript 的类型系统,使得类型操作更加灵活和强大。

posted @ 2025-09-29 15:36  Seamless  阅读(10)  评论(0)    收藏  举报