javascripttypescriptmassivejs

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. In my case, the library is Massive,js, and here are the type definitions.

The problem is that some functions should return either Promise<T[]> or Promise<T>, but the typings say it's always 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>?


Solution

  • 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.