In TypeScript How can I return a promise of either type Promise<void>
or Promise<any>
I'ved tried
Promise<void | any>
Promise<void> | Promise<any>
The resulting error is for Promise<void | any>
Promise<void | any>
:
error TS2794: Expected 1 arguments, but got 0. Did you forget to include 'void' in your type argument to 'Promise'?
I ran into this error when upgrading from Angular 11 -> 12. This TypeScript version now throws this error when Promise type isn't provided.
See example type error in below...
type SpecialPromise = (number: number) => Promise<void>;
const returnsSomething: SpecialPromise = (number: number) => {
return new Promise((resolve) => setTimeout(() => resolve(number), 2000));
};
const returnsVoid: SpecialPromise = (number: number) => {
return new Promise((resolve) => setTimeout(() => resolve(), 2000));
};
Promise.all([
returnsSomething(Math.random()),
returnsVoid(Math.random())
]).then((numbers) => console.log(numbers));
The problem is when I create a new promise it by default expects a type. void (nothing) is not a type.
new <T>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
A simple fix is to specify the type when creating the promise.
new Promise<void>
But still I get the error if I decide to use:
new Promise<void | any>
I think you want Promise<undefined|any>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.