映射类型
映射类型
在构建 CRUD(创建/读取/更新/删除)功能时,基于基础实体类型构建变体通常很有用。Nest 提供了几个执行类型转换的实用函数,使这项任务更加便捷。
Partial
在构建输入验证类型(也称为 DTOs)时,在同一类型上构建创建和更新变体通常很有用。例如,创建变体可能需要所有字段,而更新变体可能使所有字段都是可选的。
Nest 提供了 PartialType() 实用函数来简化这项任务并最小化样板代码。
PartialType() 函数返回一个类型(类),其中输入类型的所有属性都设置为可选。例如,假设我们有一个创建类型如下:
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) {}
info 提示
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) {}
info 提示
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) {}
info 提示
OmitType()函数从@nestjs/swagger包中导入。
Intersection
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,
) {}
info 提示
IntersectionType()函数从@nestjs/swagger包中导入。
组合
类型映射实用函数是可组合的。例如,以下代码将产生一个类型(类),该类型具有 CreateCatDto 类型的所有属性,除了 name,并且这些属性将设置为可选:
export class UpdateCatDto extends PartialType(
OmitType(CreateCatDto, ['name'] as const),
) {}