Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
Typescript - Remove undeclared properties of a class

I am trying to create a DTO class. But I am having issues finding a proper way to exclude undeclared properties. So if some one tries to create a DTO class and adds extra properties that are not declared inside the class then those properties should be ignored and not be added.

import { IsString, MinLength } from 'class-validator'

export class CreateUserDto {
  @IsString()
    email: string

  @IsString()
  @MinLength(6)
    password: string

  @IsString()
    firstname: string

  @IsString()
    lastname: string

  constructor (payload: any) {
    const dto = Object.assign(this, payload)

    console.log(dto)
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

For only 4 fields, I'd rather manually type out 4 lines to assign them each, but I guess if you have more DTO's with a lot more fields it could help with a more versatile method.

Here I've used Object.entries and Object.fromEntries along with a filter to exclude properties we don't need:

const dto = Object.assign(this, Object.fromEntries(Object.entries(payload).filter(([k]) => keys.includes(k))))

And keys would be something like:

["email", ...]

You can also make this a function for reusability or even a decorator too.

Playground

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!