Home > OS >  Typescript Return anything but Promise
Typescript Return anything but Promise

Time:02-21

Is there any way to specify a function type that can return anything but a Promise?

My interface looks like this:

interface AnInterface {
    func(): AllowAnythingButAPromise;
}

I tried:

type AllowAnythingButAPromise<T> = T extends Exclude<any, Promise<any>> ? T: never;
type AllowAnythingButAPromise<T> = T extends Exclude<any, Promise<unknown>> ? T: never;
type AllowAnythingButAPromise<T> = T extends Promise<unknown> ? never : T;
type AllowAnythingButAPromise<T> = T extends Promise<any> ? never : T;


type anything = number | symbol | string | boolean | null | undefined | object | Function;
type AllowAnythingButAPromise<T> = T extends Exclude<anything, Function> ? T: never;

With no luck so far... Is this even possible?

CodePudding user response:

There isn't a supported way to do negated types. There are various work arounds to get some use cases to work.

In your case, I would opt for a return type that is a union of primitive types and an object type where the then property is optional and typed as undefined, ensuring nothing with a then property is assignable to the return type. This might carve out a bit more than you like, but it might be an acceptable compromise.

interface AnInterface {
    func(): number | boolean | string| symbol | { then?: never, [n: string]: unknown };
}

Playground Link

  • Related