【问题标题】:Typescript any | any[] as function parameter打字稿任何 | any[] 作为函数参数
【发布时间】:2022-01-02 20:03:40
【问题描述】:

我一直在使用一些验证中间件,我想扩展它以允许类 (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[] 声明为函数的输入参数的方法是什么?或者如何更改函数签名以使其成功确定输入字符串是否包含类型或类型数组?

谢谢。

【问题讨论】:

    标签: javascript typescript class-transformer


    【解决方案1】:

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

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

    TypeScript playground

    【讨论】:

    • 谢谢,我相信我可以更清楚地看到错误是在哪里引入的。
    猜你喜欢
    • 2019-09-20
    • 2022-11-11
    • 2023-01-17
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2020-05-11
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多