Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
Allow property to be an array or plain type

I was trying to be able to pass the property as an array of strings or just a string value.

class GetUsersDTO {
  // @IsArray() | @IsString()
  readonly status;
}

But it's not possible even though it's a common use case. Can we do it with a plain class-validator package?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You'll need to make your own custom validator for this. Typescript doesn't reflect generics (yes, a union type is a special generic) and because of that, class-validator won't be able to properly figure out which of the two decorators to use.

import { ValidatorConstraint, ValidatorConstraintInterface, ValidationArguments } from 'class-validator';

@ValidatorConstraint({ name: 'customText', async: false })
export class IsArrayOrString implements ValidatorConstraintInterface {
  validate(val: string | string[], args: ValidationArguments) {
    const isArray = Array.isArray(val);
    const isString = typeof val === 'string';
    return isArray || isString
  }
}

And now you can use it like

class GetUsersDTO {
  @Validate(IsArrayOrString)
  readonly status: string | string[];
}

My personal word of warning: using multiple allowed inputs to the same endpoint usually brings nothing but trouble and headache. If possible, keep them separate.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda