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

232
Views
Typescript any | any[] as function parameter

I have been working with some validation middleware which I would like to extend to allow both classes (any) and arrays (any[]) as input. The class type is being used as an input parameter, and I have been able to successfully change the function to accept array types as well. The problem arises when I try to allow both types and to feed input to the function. As follows

import { plainToClass } from 'class-transformer';
import { validate, ValidationError } from 'class-validator';

const validateType = (
  type: any | any[],
  value: string,
): void => {
    validate(plainToClass(type, value), { }).then((errors: ValidationError[]) => {
        if (errors.length > 0) {
            console.log(`Errors found`);
        } else {
            console.log(`Success`);
        }
    });

This function will compile if I give a class as input, but fails when given an array;

class CreateObjectDto {
  public a: string;
  public b: string;
}

const inputString = "{a: \"something\", b: \"else\"}"
const inputArray = "[{a: \"something\", b: \"else\"}, {a: \"another\", b: \"more\"}]"

validateType(CreateObjectDto, inputString); // pass
validateType(CreateObjectDto, inputArray); // fail

If I modify the function accept only arrays (type: any[]), the function succeeds when run. I have not been able to figure out a way to type the input type as an array to allow the function to accept both data types.

What would be the way to declare CreateObjectDto[] as an input parameter to the function? Or how can I change the function signature to allow it to successfully determine whether the input string contains a type or an array of types?

Thanks.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you need a function signature which takes any or any[] then you need to write an implementation that discriminates the type and handles the argument appropriately like this:

function validateType(
  type: any | any[],
  value: string,
): void {
  if (type instanceof Array) {
    type // any[]
  } else {
    type // any
  }
}

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