Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Void[] Array Not Assignable to Type Void

Tags:

typescript

I expect type void[] to be compatible with type void. Specifically, when using Promise.all.

class Foo {
  delete(): Promise<void> {
    // do delete
    return Promise.resolve();
  }
  deleteMany(list: Foo[]): Promise<void> {
    return Promise.all(list.map((x) => x.delete()));
  }

typescript error:

'Type 'Promise<void[]>' is not assignable to type 'Promise<void>'. Type 'void[]' is not assignable to type 'void'.'

I can solve this two ways that I know of:

  1. Mark deleteMany as returning Promise<void[]>.
  2. Promise chain to Promise.all, to return a resolved promise. e.g.

    return Promise.all(list.map((x) => x.delete())).then(() => Promise.resolve());
    

The second one is worse, since that bit of code executes in JavaScript, but the first one is confusing to developers. Does Typescript have poor support for Promise.all or is it omitted from their documentation? Anyone find a better solution?

like image 896
Jerroyd M. Avatar asked Apr 24 '17 20:04

Jerroyd M.


People also ask

Is not assignable to type () => void?

The "Type 'void' is not assignable to type" TypeScript error occurs when we forget to return a value from a function, so the function gets an implicit return type of void . To solve the error, make sure you return a value of the correct type from your functions before the assignment.

What does () => void mean TypeScript?

Function Type Expressions The syntax (a: string) => void means “a function with one parameter, named a , of type string, that doesn't have a return value”. Just like with function declarations, if a parameter type isn't specified, it's implicitly any .


1 Answers

The 1 (Mark deleteMany as returning Promise<void[]>) is absolutely ok at least for me.

However, you can use async/await if you really want to return Promise<void>:

class Foo {
  delete(): Promise<void> {
    // do delete
    return Promise.resolve();
  }
  async deleteMany(list: Foo[]): Promise<void> {
    await Promise.all(list.map((x) => x.delete()));
  }

The function will behave exactly the same way.

like image 172
Erik Cupal Avatar answered Oct 25 '22 17:10

Erik Cupal