Borislav Hadzhiev
Thu Mar 17 2022·2 min read
Photo by Andrey Larin
The error "Expected 1 argument, but got 0. Did you forget to include 'void' in
your type argument to Promise" occurs when we use the Promise
constructor
without passing it an argument. To solve the error, use a generic to type the
value of the Promise
to void
.
Here is an example of how the error occurs.
function getPromise() { return new Promise((resolve, reject) => { // ⛔️ Error: Expected 1 arguments, but got 0. // Did you forget to include 'void' in your // type argument to 'Promise'?ts(2794) resolve(); }); }
We used the Promise() constructor without resolving it with a value.
Promise
constructor takes 1 argument of type unknown
, so we should either pass it an argument or update the type of its parameters.To solve the error in this specific situation, pass void
to the generic of the
Promise
constructor.
function getPromise() { // 👇️ type Promise value as void return new Promise<void>((resolve, reject) => { resolve(); }); }
The void type represents the return value of a function that doesn't return anything.
When a function definition has a void
return type, it means the function must
not return anything.
If you need to resolve the Promise
with a value of another type, pass the
specific type to the
generic.
function getPromise() { return new Promise<number>((resolve, reject) => { resolve(1000); }); }
The Promise above can only be resolved with a number.
If your Promise may get resolved with multiple types, use a union type.
function getPromise() { return new Promise<number | string>((resolve, reject) => { if (Math.random() > 0.5) { resolve(1000); } resolve('hello world'); }); }
The promise in the example can be resolved with a value of type number
or
string
.
Note that you should also use the Promise generic if you have to specify the return type of a function that returns a Promise.
async function getPromise(): Promise<number> { return 42; }
We declared an async function in the example.
async
function it gets wrapped in a Promise
. In other words, an async
function is always going to return a Promise
.If you need to explicitly type the function's return type, you have to use the
Promise
generic just like we did in the previous examples.