Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在TypeScript中生成typesafe联合类型表单函数_Javascript_Typescript - Fatal编程技术网

Javascript 如何在TypeScript中生成typesafe联合类型表单函数

Javascript 如何在TypeScript中生成typesafe联合类型表单函数,javascript,typescript,Javascript,Typescript,我有一个函数,它接受单个值或值数组,并根据它返回新值,单个值或数组。然后该值检查类型,无法确定返回值是单个还是数组 如何使类型脚本理解我传递给函数数组的当前值和返回值将是数组 prepareForResponseMany2(data: ProductEntity | ProductEntity[]): ProductType | ProductType[] { if (Array.isArray(data)) { return data.map(entity =>

我有一个函数,它接受单个值或值数组,并根据它返回新值,单个值或数组。然后该值检查类型,无法确定返回值是单个还是数组

如何使类型脚本理解我传递给函数数组的当前值和返回值将是数组

  prepareForResponseMany2(data: ProductEntity | ProductEntity[]): ProductType | ProductType[] {
    if (Array.isArray(data)) {
      return data.map(entity => this.prepareForResponse(entity));
    }

    return this.prepareForResponse(data);
  }

看来你需要使用它来实现你想要的。因此,您可以创建一个接口,例如:

  prepareForResponseMany2(data: ProductEntity, ): ProductType;
  prepareForResponseMany2(data: ProductEntity[], ): ProductType[];
  prepareForResponseMany2(data: any): ProductType | ProductType[] {
    if (Array.isArray(data)) {
      return data.map(entity => this.prepareForResponse(entity));
    }

    return this.prepareForResponse(data);
  }

在这种情况下,返回值的类型将取决于传递到方法中的参数类型。

似乎需要使用来实现所需的功能。因此,您可以创建一个接口,例如:

  prepareForResponseMany2(data: ProductEntity, ): ProductType;
  prepareForResponseMany2(data: ProductEntity[], ): ProductType[];
  prepareForResponseMany2(data: any): ProductType | ProductType[] {
    if (Array.isArray(data)) {
      return data.map(entity => this.prepareForResponse(entity));
    }

    return this.prepareForResponse(data);
  }
在这种情况下,返回值的类型将取决于传入方法的参数类型。

您可以使用
(someValue作为ProductType[])
(someValue)

您可以使用
(someValue作为ProductType[])
(someValue)


我认为添加一个实际解决方案的示例会更有帮助实际上,声明
any
将允许返回无效值。它应该是
prepareForResponseMany2(数据:ProductEntity | ProductEntity[]){…}
实际上不是,最后的重载应该是宽的。我刚刚检查了它,您无法将任何值传递给该方法,因此,您始终可以获得正确的返回类型。关于输入类型,您是正确的,而不是关于返回类型。如果它是
any
函数可以返回任何内容,并且不会出现编译警告:您是最好的!!我认为添加一个实际解决方案的示例会更有帮助实际上,声明
any
将允许返回无效值。它应该是
prepareForResponseMany2(数据:ProductEntity | ProductEntity[]){…}
实际上不是,最后的重载应该是宽的。我刚刚检查了它,您无法将任何值传递给该方法,因此,您始终可以获得正确的返回类型。关于输入类型,您是正确的,而不是关于返回类型。如果它是
any
函数可以返回任何内容,并且不会出现编译警告:您是最好的!!所以没有办法让ts自动解决它?因为我每次都要写,所以没有办法让ts自动解析?因为我每次都要写