Alex Ironside
Alex Ironside

Reputation: 5059

Merging two classes

I have two classes.

UserDto

export class UserDto {
  name: string;
}

AuthDto

export class AuthDto {
    email: string;
    password: string;
}

I want to create a class of RegistrationDto, which will be a merge of these two classes.

I tried to do this

export class RegisterDto extends UserDto, AuthDto {}

But this only works for interfaces. I am using it as Nestjs dtos, so if I'm thinking about it in the wrong way, please let me know.

How do I handle the classes in this case?

Upvotes: 1

Views: 1676

Answers (3)

Istiyak Tailor
Istiyak Tailor

Reputation: 1875

You can combine both the DTO's into one using the Intersection Type

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

export class RegisterDto extends IntersectionType(
  AuthDto,
  UserDto,
) {}

Reference: https://docs.nestjs.com/openapi/mapped-types#intersection

Upvotes: 2

Alexandros T
Alexandros T

Reputation: 36

Why don't you consolidate them to a new class:

export class RegisterDto{
    authDto: AuthDto;
    userDto: UserDto;
}

Upvotes: 1

Maverick Fabroa
Maverick Fabroa

Reputation: 1183

You can extend AuthDto to UserDto or vice-versa:

export class AuthDto extends UserDto {
    email: string;
    password: string;
}

And then do this:

export class RegisterDto extends AuthDto {}

Just a suggestion

Upvotes: 2

Related Questions