Skip to content

映射类型

在构建 CRUD(创建/读取/更新/删除)等功能时,通常需要基于一个基础实体类型构造出不同的变体。Nest 提供了多个实用函数来执行类型转换,使这项工作更加便捷。

Partial

在构建输入验证类型(也称为 DTO)时,经常需要针对同一类型构建 createupdate 两种变体。例如,create 变体可能要求所有字段都是必填的,而 update 变体则可能将所有字段设为可选。

Nest 提供了 PartialType() 实用函数,使这项工作更加简单,同时减少样板代码。

PartialType() 函数返回一个类型(类),其中输入类型的所有属性都被设为可选。例如,假设我们有如下 create 类型:

typescript
import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
  @ApiProperty()
  name: string;

  @ApiProperty()
  age: number;

  @ApiProperty()
  breed: string;
}

默认情况下,所有这些字段都是必填的。要创建一个具有相同字段但每个字段都可选的类型,可以使用 PartialType(),并将类引用(CreateCatDto)作为参数传入:

typescript
export class UpdateCatDto extends PartialType(CreateCatDto) {}

提示

PartialType() 函数从 @nestjs/swagger 包中导入。

Pick

PickType() 函数通过从输入类型中选取一组属性来构造一个新类型(类)。例如,假设我们有如下类型:

typescript
import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
  @ApiProperty()
  name: string;

  @ApiProperty()
  age: number;

  @ApiProperty()
  breed: string;
}

我们可以使用 PickType() 实用函数从该类中选取一组属性:

typescript
export class UpdateCatAgeDto extends PickType(CreateCatDto, ['age'] as const) {}

提示

PickType() 函数从 @nestjs/swagger 包中导入。

Omit

OmitType() 函数通过从输入类型中选取所有属性,然后移除特定的一组键来构造类型。例如,假设我们有如下类型:

typescript
import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
  @ApiProperty()
  name: string;

  @ApiProperty()
  age: number;

  @ApiProperty()
  breed: string;
}

我们可以生成一个除 name 之外包含所有属性的派生类型,如下所示。在这种写法中,OmitType 的第二个参数是一个属性名称数组。

typescript
export class UpdateCatDto extends OmitType(CreateCatDto, ['name'] as const) {}

提示

OmitType() 函数从 @nestjs/swagger 包中导入。

Intersection

IntersectionType() 函数将两个类型合并为一个新类型(类)。例如,假设我们有如下两个类型:

typescript
import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
  @ApiProperty()
  name: string;

  @ApiProperty()
  breed: string;
}

export class AdditionalCatInfo {
  @ApiProperty()
  color: string;
}

我们可以生成一个包含两个类型中所有属性的新类型:

typescript
export class UpdateCatDto extends IntersectionType(
  CreateCatDto,
  AdditionalCatInfo,
) {}

提示

IntersectionType() 函数从 @nestjs/swagger 包中导入。

组合使用

类型映射实用函数支持组合使用。例如,以下代码会生成一个类型(类),它包含 CreateCatDto 类型中除 name 之外的所有属性,并且这些属性都被设为可选:

typescript
export class UpdateCatDto extends PartialType(
  OmitType(CreateCatDto, ['name'] as const),
) {}

基于 NestJS 官方文档翻译