简体   繁体   English

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

[英]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.我一直在使用一些验证中间件,我想扩展它以允许类(任何)和 arrays(任何 [])作为输入。 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. class 类型被用作输入参数,我已经能够成功地将 function 更改为也接受数组类型。 The problem arises when I try to allow both types and to feed input to the function.当我尝试同时允许这两种类型并向 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 作为输入,则此 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

If I modify the function accept only arrays (type: any[]), the function succeeds when run.如果我修改 function 只接受 arrays (类型:any[]),则 function 在运行时成功。 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.我还没有找到一种将输入类型键入为数组以允许 function 接受这两种数据类型的方法。

What would be the way to declare CreateObjectDto[] as an input parameter to the function?将 CreateObjectDto[] 声明为 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?或者如何更改 function 签名以使其成功确定输入字符串是否包含类型或类型数组?

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

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

TypeScript playground TypeScript操场

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

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