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

240
Vistas
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 Respuestas
Responde la pregunta

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