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:
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?
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With