简体   繁体   English

在TypeScript中,定义可返回Promise的函数的最佳方法是什么? <T> 或承诺 <T[]> ?

[英]In TypeScript, what is the best way to define a function that can return either Promise<T> or Promise<T[]>?

I'm just starting with TypeScript and I ran across a situation in which the type definitions for a library I'm using is wrong. 我只是从TypeScript开始,我遇到了一种情况,在这种情况下,我正在使用的库的类型定义错误。 In my case, the library is Massive,js , and here are the type definitions . 就我而言,该库是Massive,js这是类型定义

The problem is that some functions should return either Promise<T[]> or Promise<T> , but the typings say it's always Promise<T[]> . 问题在于某些函数应该返回Promise<T[]>Promise<T> ,但是类型表明它始终是Promise<T[]>

  interface Table<T> {
    // other functions omitted for simplicity
    save(data: object): Promise<T[]>;
    insert(data: object): Promise<T[]>;
    update(dataOrCriteria: object, changesMap?: object): Promise<T[]>;
  }

How do I fix the above functions so they would return either Promise<T[]> or Promise<T> ? 如何修复以上函数,以便它们返回Promise<T[]>Promise<T>

You can define multiple types. 您可以定义多种类型。

interface Table<T> {
    // other functions omitted for simplicity
    save(data: object): Promise<T | T[]>;
    insert(data: object): Promise<T | T[]>;
    update(dataOrCriteria: object, changesMap?: object): Promise<T | T[]>;
  }

Or when using the library just make T an array of items. 或者在使用库时,只需将T设置为项目数组即可。

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

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