Mapped Type

CRUD(Create, Read, Update, Delete)와 같은 기능을 구축할 때 기본 항목 유형을 변형하여 사용하면 편리합니다.

Nest 는 이 작업을 보다 편리하게 만들기 위해 유형 변환을 수행하는 몇 가지 유틸리티 함수들을 제공합니다.

PartialType

POST, UPDATE 요청 처리 시 데이터 삽입에 대한 DTO, 데이터 수정에 대한 DTO를 만듭니다. 일반적으로 데이터 수정 DTO는 삽입 시의 DTO에 종속됩니다. 수정 시의 DTO에 들어가는 개체가 삽입 시의 DTO에 들어 있는 개체에 포함된다는 것입니다. 

이런 상황에서 사용할 수 있는 것이 PartialType입니다.

PartialType() 함수는 입력 유형의 모든 속성이 선택 사항으로 설정된 유형(클래스)을 반환합니다.

예시) 다음과 같이 POST 처리를 위한 Dto 가 있습니다.

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

export class CreateUserDto {
  @ApiProperty()
  email: string;
  
  @ApiProperty()
  password: string;
  
  @ApiProperty()
  nickname: string;
}

기본적으로 모든 필드들이 필수값입니다. PartialType() 함수를 사용하면 같은 필드를 가지지만 각 필드가 옵셔널을 가지는 타입을 생성할 수 있습니다.

export class UpdateUserDto extends PartialType(CreateUserDto) {}

 

PickType

PickType() 함수는 입력 유형에서 속성 집합을 선택하여 새로운 유형(클래스)을 생성합니다.

예시) 다음과 같이 POST 처리를 위한 Dto 가 있습니다.

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

export class CreateUserDto {
  @ApiProperty()
  email: string;
  
  @ApiProperty()
  password: string;
  
  @ApiProperty()
  nickname: string;
}

아래와 같이 PickType() 함수를 사용해서 CreateUserDto로부터 email 프로퍼티만을 선택해 UpdateUserDto 를 생성할 수 있습니다.

export class UpdateUserDto extends PickType(CreateUserDto, ['email'] as const) {}

OmitType

OmitType() 함수는 입력 타입에서 모든 속성을 선택한 다음 특정 키 세트를 제거해 타입을 구성합니다.

예시)

export class UpdateUserDto extends OmitType(CreateUserDto, ['password'] as const) {}

IntersectionType

IntersectionType() 함수는 두 타입을 하나의 새로운 타입(클래스)으로 결합합니다.

export class CreateUserDto {
  email: string;
  password: string;
  nickname: string;
}

export class AdditionalUserInfo {
  profileImagePath: string;
}
export class UpdateUserDto extends IntersectionType(
  CreateUserDto,
  AdditionalUserInfo
) {}

출처

https://docs.nestjs.com/openapi/mapped-types 

복사했습니다!