TypeScript 工具类型详解与示例

在这篇博客中,我们将深入了解 TypeScript 中的工具类型。工具类型是 TypeScript 提供的一组实用的类型,它们可以帮助我们进行更复杂的类型操作。

1. Partial

Partial<T> 类型将输入类型 T 的所有属性设为可选。这在需要部分更新对象时特别有用。

interface Person {
  name: string;
  age: number;
}

function updatePerson(person: Person, updates: Partial<Person>): Person {
  return { ...person, ...updates };
}

const person: Person = { name: "John", age: 30 };
const updatedPerson = updatePerson(person, { age: 31 });

2. Required

Partial<T> 相反,Required<T> 类型将输入类型 T 的所有属性设为必需。

interface Employee {
  name: string;
  age?: number;
}

function createEmployee(employee: Required<Employee>): Employee {
  return { ...employee };
}

const newEmployee = createEmployee({ name: "Jane", age: 28 });

3. Readonly

Readonly<T> 类型将输入类型 T 的所有属性设为只读。

interface Book {
  title: string;
  author: string;
}

const myBook: Readonly<Book> = { title: "The Alchemist", author: "Paulo Coelho" };
myBook.title = "Another Title"; // Error: Cannot assign to 'title' because it is a read-only property

4. Pick<T, K>

Pick<T, K> 类型从输入类型 T 中选取一组属性 K,创建一个新类型。

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

type UserNameAndEmail = Pick<User, "name" | "email">;

function getUserInfo(user: UserNameAndEmail): void {
  console.log(`${user.name} <${user.email}>`);
}

5. Omit<T, K>

Omit<T, K> 类型从输入类型 T 中排除一组属性 K,创建一个新类型。

interface Address {
  street: string;
  city: string;
  country: string;
  zipCode: string;
}

type AddressWithoutZip = Omit<Address, "zipCode">;

function printAddress(address: AddressWithoutZip): void {
  console.log(`${address.street}, ${address.city}, ${address.country}`);
}

6. Extract<T, U>

Extract<T, U> 类型从类型 T 中提取可以赋值给类型 U 的类型。

type Fruit = "apple" | "banana" | "orange" | "pear";
type Citrus = "orange" | "lemon" | "lime" | "grapefruit";

type CitrusFruit = Extract<Fruit, Citrus>; // "orange"

7. Exclude<T, U>

Exclude<T, U> 类型从类型 T 中排除可以赋值给类型 U 的类型。这在我们需要从联合类型中移除某些类型时非常有用。
Exclude<T, U> 类型从类型 T 中排除可以赋值给类型 U 的类型。这在我们需要从联合类型中移除某些类型时非常有用。

type Colors = "red" | "green" | "blue" | "yellow" | "purple";
type PrimaryColors = "red" | "green" | "blue";

type SecondaryColors = Exclude<Colors, PrimaryColors>; // "yellow" | "purple"

在上述示例中,我们定义了一个 Colors 联合类型,然后使用 Exclude<T, U> 工具类型从 Colors 中排除 PrimaryColors。得到的结果是一个新的联合类型 SecondaryColors,仅包含 “yellow” 和 “purple”。

8. NonNullable

NonNullable<T> 类型从输入类型 T 中排除 nullundefined 类型。这对于确保某个类型的值不为 nullundefined 是非常有用的。

type NullableValues = string | number | null | undefined;

type NonNullableValues = NonNullable<NullableValues>; // string | number

在上述示例中,我们定义了一个 NullableValues 联合类型,然后使用 NonNullable<T> 工具类型从 NullableValues 中排除 nullundefined 类型。得到的结果是一个新的联合类型 NonNullableValues,仅包含 stringnumber 类型。

9. ReturnType

ReturnType<T> 类型获取函数类型 T 的返回类型。这对于需要处理函数返回值的场景非常有用。

function greet(name: string): string {
  return `Hello, ${name}!`;
}

type Greeting = ReturnType<typeof greet>; // string

在上述示例中,我们定义了一个 greet 函数,并使用 ReturnType<T> 工具类型获取该函数的返回类型。得到的结果是一个 Greeting 类型,等于 string

10. InstanceType

InstanceType<T> 类型获取构造函数类型 T 的实例类型。这对于处理类实例时非常有用。

class Animal {
  constructor(public name: string, public species: string) {}
}

type AnimalInstance = InstanceType<typeof Animal>; // Animal

在上述示例中,我们定义了一个 Animal 类,并使用 InstanceType<T> 工具类型获取该类的实例类型。得到的结果是一个 AnimalInstance 类型,等于 Animal

您可以根据需求灵活运用这些工具类型来帮助您处理更复杂的类型操作。在实际项目中,这些工具类型对于提高代码质量和可维护性非常有帮助。

原文链接:https://juejin.cn/post/7212924329428713530 作者:XinD

(0)
上一篇 2023年3月22日 上午11:10
下一篇 2023年3月22日 下午7:00

相关推荐

发表评论

登录后才能评论