映射类型
在构建 CRUD(创建/读取/更新/删除)这类功能时,通常需要基于某个基础实体类型构造出它的各种变体。Nest 提供了一组执行类型转换的工具函数,让这项工作更省事。
Partial
构建输入校验类型(也称 DTO,即数据传输对象)时,常常需要在同一个类型上构造 create 与 update 两个变体。例如,create 变体可能要求所有字段必填,而 update 变体则把所有字段都设为可选。
Nest 提供了 PartialType() 工具函数来简化这项任务、最大限度减少样板代码。
PartialType() 函数返回一个类型(类),其中所有属性都取自输入类型并被设为可选。例如,假设你有如下一个 create 类型:
import { ApiProperty } from '@nestjs/swagger';
export class CreateCatDto {
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}默认情况下,这些字段全部必填。要创建一个字段相同、但每个字段都可选的类型,请使用 PartialType() 并把类引用(CreateCatDto)作为参数传入:
export class UpdateCatDto extends PartialType(CreateCatDto) {}PartialType() 函数从 @nestjs/swagger 包导入。
Pick
PickType() 函数从输入类型中挑选一组属性,据此构造出一个新的类型(类)。例如,假设你以如下类型为起点:
import { ApiProperty } from '@nestjs/swagger';
export class CreateCatDto {
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}你可以用 PickType() 工具函数从这个类中挑选一组属性:
export class UpdateCatAgeDto extends PickType(CreateCatDto, ['age'] as const) {}PickType() 函数从 @nestjs/swagger 包导入。
Omit
OmitType() 函数先取输入类型的全部属性,再移除特定的那组键,据此构造出一个类型。例如,假设你以如下类型为起点:
import { ApiProperty } from '@nestjs/swagger';
export class CreateCatDto {
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}你可以生成一个除 name 之外 包含其余全部属性的派生类型,如下所示。在这种写法中,OmitType() 的第二个参数是属性名组成的数组。
export class UpdateCatDto extends OmitType(CreateCatDto, ['name'] as const) {}OmitType() 函数从 @nestjs/swagger 包导入。
交叉类型
IntersectionType() 函数把两个或更多类型合并为一个新的类型(类)。例如,假设你以如下两个类型为起点:
import { ApiProperty } from '@nestjs/swagger';
export class CreateCatDto {
@ApiProperty()
name: string;
@ApiProperty()
breed: string;
}
export class AdditionalCatInfo {
@ApiProperty()
color: string;
}你可以生成一个合并了两个类型全部属性的新类型:
export class UpdateCatDto extends IntersectionType(
CreateCatDto,
AdditionalCatInfo,
) {}IntersectionType() 函数从 @nestjs/swagger 包导入。
组合
这些类型映射工具函数是可组合的。例如,下面的代码生成一个类型(类),它包含 CreateCatDto 类型除 name 之外的全部属性,且这些属性都被设为可选:
export class UpdateCatDto extends PartialType(
OmitType(CreateCatDto, ['name'] as const),
) {}