Skip to Content
BackendNestJs39-Mapped Types

1. Mapped Types 정리

  • Partial : 클래스의 프로퍼티 정의를 모두 optional로 만든다
  • Pick : 특정 프로퍼티만 골라 사용 할 수 있다. (Omit의 반대)
  • Omit : 특정 프로퍼티만 생략 할 수 있다. (Pick의 반대)
  • Intersection : 두 타입의 프로퍼티를 모두 모아서 사용 할 수 있다
  • Composition : Mapped Types를 다양하게 조합해서 중첩 적용 가능하다

2. Partial

typescript
1
export class CreateUserDto {
2
@IsString()
3
readonly name: string
4
5
@IsEmail()
6
readonly email: string
7
8
@IsString()
9
readonly password: string
10
}
typescript
1
export class UpdateUserDto extends PartialType(CreateUserDto) {}
2
/*
3
{
4
name?: string;
5
email?: string;
6
password?: string;
7
}
8
*/

3. Pick

typescript
1
export class CreateUserDto {
2
@IsString()
3
readonly name: string
4
5
@IsEmail()
6
readonly email: string
7
8
@IsString()
9
readonly password: string
10
}
typescript
1
export class LoginUserDto extends PickType(CreateUserDto, ['email', 'password'] as const) {}
2
/*
3
{
4
email: string;
5
password: string;
6
}
7
*/

4. Omit

typescript
1
export class CreateUserDto {
2
@IsString()
3
readonly name: string
4
5
@IsEmail()
6
readonly email: string
7
8
@IsString()
9
readonly password: string
10
}
typescript
1
export class PublicUserDto extends OmitType(CreateUserDto, ['password'] as const) {}
2
/*
3
{
4
name: string;
5
email: string;
6
}
7
*/

5. Intersection

typescript
1
export class UserDetailDto {
2
@IsString()
3
readonly name: string
4
5
@IsEmail()
6
readonly email: string
7
}
8
9
export class AddressDto {
10
@IsString()
11
readonly street: string
12
13
@IsString()
14
readonly city: string
15
16
@IsString()
17
readonly country: string
18
}
typescript
1
export class UserWithAddressDto extends IntersectionType(UserDetailDto, AddressDto) {}
2
/*
3
{
4
name: string;
5
email: string;
6
street: string;
7
city: string;
8
country: string;
9
}
10
*/

6. Composition

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