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

148
Views
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 answers
Answer question

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 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!