返回

TypeScript 一些你可能不知道的工具泛型使用及其实现

前端

Partial

Partial 将 T 中的所有属性标记为可选。这在创建新对象时非常有用,我们希望允许某些属性为 undefined。

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

const partialPerson: Partial<Person> = {
  name: 'Alice',
};

Required

Required 将 T 中的所有属性标记为必需。这在确保对象始终具有某些属性时非常有用。

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

const requiredPerson: Required<Person> = {
  name: 'Alice',
  age: 25,
};

Readonly

Readonly 将 T 中的所有属性标记为只读。这有助于防止意外地修改对象。

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

const readonlyPerson: Readonly<Person> = {
  name: 'Alice',
  age: 25,
};

readonlyPerson.name = 'Bob'; // Error: Cannot assign to read-only property 'name'

Record

Record<K, V> 创建一个以 K 为键类型、V 为值类型的对象类型。

type KeyValue<T> = Record<string, T>;

const person: KeyValue<string> = {
  name: 'Alice',
  age: '25',
};

Pick

Pick<T, K> 从 T 中选取具有指定键 K 的属性,创建一个新的类型。

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

type PersonName = Pick<Person, 'name'>;

const personName: PersonName = {
  name: 'Alice',
};

Omit

Omit<T, K> 从 T 中排除具有指定键 K 的属性,创建一个新的类型。

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

type PersonWithoutAddress = Omit<Person, 'address'>;

const personWithoutAddress: PersonWithoutAddress = {
  name: 'Alice',
  age: 25,
};

Exclude

Exclude<T, U> 从 T 中排除 U 中的类型,创建一个新的类型。

type Primitive = string | number | boolean;
type NonPrimitive = Exclude<any, Primitive>;

// NonPrimitive 等于 object | Function | symbol

Extract

Extract<T, U> 从 T 中提取 U 中的类型,创建一个新的类型。

type Primitive = string | number | boolean;
type NonPrimitive = Extract<any, Primitive>;

// NonPrimitive 等于 never

NonNullable

NonNullable 从 T 中排除 null 和 undefined,创建一个新的类型。

type Person = {
  name: string | null;
  age: number | undefined;
};

type NonNullablePerson = NonNullable<Person>;

const nonNullablePerson: NonNullablePerson = {
  name: 'Alice',
  age: 25,
};

Parameters

Parameters 获取一个构造函数或函数类型 T 的参数类型。

function sum(a: number, b: number): number {
  return a + b;
}

type SumParameters = Parameters<typeof sum>;

// SumParameters 等于 [number, number]

ConstructorParameters

ConstructorParameters 获取一个构造函数类型 T 的构造参数类型。

class Person {
  constructor(name: string, age: number) {}
}

type PersonConstructorParameters = ConstructorParameters<typeof Person>;

// PersonConstructorParameters 等于 [string, number]

ReturnType

ReturnType 获取一个函数类型 T 的返回类型。

function sum(a: number, b: number): number {
  return a + b;
}

type SumReturnType = ReturnType<typeof sum>;

// SumReturnType 等于 number

InstanceType

InstanceType 获取一个构造函数类型 T 的实例类型。

class Person {
  constructor(name: string, age: number) {}
}

type PersonInstance = InstanceType<typeof Person>;

// PersonInstance 等于 Person

通过使用这些工具泛型,我们可以更轻松地编写类型安全的 TypeScript 代码,并创建更加健壮和可维护的应用程序。