Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

231
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda