0

我一直在使用一些验证中间件,我想扩展它以允许类(any)和数组(any[])作为输入。类类型被用作输入参数,我已经能够成功地将函数更改为接受数组类型。当我尝试允许这两种类型并将输入提供给函数时,就会出现问题。如下

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`);
        }
    });

如果我将类作为输入,此函数将编译,但在给定数组时会失败;

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

如果我修改函数只接受数组(类型:any[]),则函数在运行时会成功。我还没有找到一种将输入类型键入为数组以允许函数接受这两种数据类型的方法。

将 CreateObjectDto[] 声明为函数的输入参数的方法是什么?或者如何更改函数签名以使其成功确定输入字符串是否包含类型或类型数组?

谢谢。

4

1 回答 1

1

如果您需要一个函数签名,any或者any[]您需要编写一个区分类型并适当处理参数的实现,如下所示:

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

TypeScript 游乐场

于 2022-01-02T12:02:47.923 回答