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