Skip to content

TypeScript泛型(Generics)

泛型

TypeScript 中有许多内置的泛型类型和方法,这些类型和方法可以帮助我们更好地处理和操作泛型类型。以下是一些常用的 TypeScript 内置泛型类型和方法:

  1. Partial<T>: 将类型 T 的所有属性设置为可选。
  2. Required<T>: 将类型 T 的所有属性设置为必选。
  3. Pick<T, K>: 从类型 T 中选择部分属性,并生成一个新的类型。
  4. Omit<T, K>: 从类型 T 中排除指定属性,并生成一个新的类型。
  5. Record<K, T>: 创建一个具有键类型 K 和值类型 T 的新对象类型。
  6. Exclude<T, U>: 从类型 T 中排除可以赋值给 U 的所有属性。
  7. Extract<T, U>: 从类型 T 中提取可以赋值给 U 的所有属性。
  8. ReturnType<T>: 获取函数类型 T 的返回类型。
  9. Parameters<T>: 获取函数类型 T 的参数类型组成的元组类型。
  10. ConstructorParameters<T>: 获取构造函数类型 T 的参数类型组成的元组类型。
  11. InstanceType<T>: 获取构造函数类型 T 的实例类型。

这些内置的泛型类型和方法可以帮助我们更好地利用 TypeScript 的类型系统来进行类型操作和转换。根据具体的需求,选择合适的泛型类型和方法可以让我们更高效地编写类型安全的代码。

以下是关于上述提到的一些常用 TypeScript 内置泛型类型和方法的具体使用示例:

  1. Partial<T>:
typescript
interface User {
    id: number;
    name: string;
    age: number;
}

function updateUser(user: Partial<User>): void {
    // 更新用户信息
}

const partialUser: Partial<User> = {
    name: 'Alice'
};

updateUser(partialUser);
  1. Required<T>:
typescript
interface Props {
    id?: number;
    name?: string;
    age?: number;
}

function processProps(props: Required<Props>): void {
    // 处理必选属性
}

// 这里会报错,因为缺少必选属性
// processProps({});

processProps({ id: 1, name: 'Bob', age: 30 });
  1. Pick<T, K>:
typescript
interface User {
    id: number;
    name: string;
    age: number;
    email: string;
}

type UserBasicInfo = Pick<User, 'id' | 'name'>;

const userBasicInfo: UserBasicInfo = {
    id: 1,
    name: 'Alice'
};
  1. Omit<T, K>:
typescript
interface User {
    id: number;
    name: string;
    age: number;
    email: string;
}

type UserWithoutEmail = Omit<User, 'email'>;

const userWithoutEmail: UserWithoutEmail = {
    id: 1,
    name: 'Bob',
    age: 30
};

这些示例展示了如何使用 TypeScript 内置的泛型类型和方法来操作和转换类型,以满足特定需求。通过合理地利用这些内置泛型类型和方法,我们可以更好地定义和处理 TypeScript 中的类型,确保代码的类型安全性。

当使用 TypeScript 中的 Record、Exclude、Extract 等类型时,可以在代码中灵活地定义和操作类型。以下是这些类型的具体用法示例:

  1. Record<K, T>:
typescript
type Fruit = 'Apple' | 'Banana' | 'Orange';
type FruitInventory = Record<Fruit, number>;

const fruitStock: FruitInventory = {
    Apple: 10,
    Banana: 20,
    Orange: 15
};
  1. Exclude<T, U>:
typescript
type NumberOrString = number | string;
type OnlyNumber = Exclude<NumberOrString, string>;

let num: OnlyNumber;
num = 10; // 正确
// num = 'hello'; // 错误,只能是数字类型
  1. Extract<T, U>:
typescript
type Color = 'Red' | 'Green' | 'Blue' | 'Yellow';
type PrimaryColor = 'Red' | 'Blue';
type PrimaryColors = Extract<Color, PrimaryColor>;

let color: PrimaryColors;
color = 'Red'; // 正确
color = 'Green'; // 错误,不是主要颜色
  1. ConstructorParameters<T>:
typescript
class Person {
    constructor(public name: string, public age: number) {}
}

type PersonConstructorParams = ConstructorParameters<typeof Person>;
// PersonConstructorParams 类型为 [string, number]

const params: PersonConstructorParams = ['Alice', 30];
const person = new Person(...params);

这些示例展示了如何使用 Record、Exclude、Extract 等类型来定义和操作 TypeScript 中的类型。通过这些类型,我们可以更好地控制和限制类型的范围,确保代码在编译时能够捕获潜在的类型错误,提高代码的类型安全性。

下面是关于 TypeScript 中 ReturnType、Parameters 和 InstanceType 的具体用法示例:

  1. ReturnType<T>:
typescript
function greet(): string {
    return 'Hello, TypeScript!';
}

type GreetReturnType = ReturnType<typeof greet>;
// GreetReturnType 类型为 string

const message: GreetReturnType = greet();
console.log(message); // 输出: Hello, TypeScript!
  1. Parameters<T>:
typescript
function createUser(name: string, age: number): void {
    // 创建用户逻辑
}

type CreateUserParams = Parameters<typeof createUser>;
// CreateUserParams 类型为 [string, number]

const params: CreateUserParams = ['Alice', 30];
createUser(...params);
  1. InstanceType<T>:
typescript
class Person {
    constructor(public name: string, public age: number) {}
}

type PersonInstanceType = InstanceType<typeof Person>;
// PersonInstanceType 类型为 Person

const person: PersonInstanceType = new Person('Alice', 30);
console.log(person); // 输出: Person { name: 'Alice', age: 30 }

这些示例展示了如何使用 ReturnType、Parameters 和 InstanceType 这些 TypeScript 内置类型来获取函数的返回类型、参数类型以及构造函数的实例类型。通过这些类型,我们可以更好地了解和操作函数和类的类型信息,从而提高代码的可读性和类型安全性。