繁体   English   中英

Typescript 任意 | 任何[] 作为 function 参数

[英]Typescript any | any[] as function parameter

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

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 作为输入,则此 function 将编译,但在给定数组时会失败;

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

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

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

谢谢。

如果您需要一个采用anyany[]的 function 签名,那么您需要编写一个区分类型并适当处理参数的实现,如下所示:

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

TypeScript操场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM