Home > front end >  Type of Resolved Promise
Type of Resolved Promise

Time:12-19

I would like to use the return type of a function to type an item on an interface like so:

const returnsPromise = async (): Promise<string> => {
  return Promise.resolve('I want the string type and not a Promise')
}

interface Myinterface {
  message: ReturnType<typeof returnsPromise>
}

However, message is of type Promise instead of string. Can one get the type a promise ought to resolve with?

CodePudding user response:

TypeScript 4.5 introduced the Awaited<T> type, which evaluates to the type you get if you await a value of type T. So you could write:

interface Myinterface {
  message: Awaited<ReturnType<typeof returnsPromise>>;
  // (property) Myinterface.message: string
}

If you don't have TypeScript 4.5 yet, you can always "un-Promise" a type yourself with conditional type inference:

type Unpromise<T> = T extends Promise<infer U> ? U : never;

interface Myinterface {
  message: Unpromise<ReturnType<typeof returnsPromise>>;
  // (property) Myinterface.message: string
}

They both produce string when you pass in Promise<string>. For more complicated types like nested Promises, they produce different results:

type APPs = Awaited<Promise<Promise<string>>>; // type APPs = string
type UPPs = Unpromise<Promise<Promise<string>>>; // type UPPs = Promise<string>

So it depends on your use cases whether you need to calculate "what a promise resolves with" recursively or not.

Playground link to code

  • Related