Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the return type of resolved promise?

Tags:

typescript

I want to create a variable with some default values, that is an extended interface of the resolved return type from a promise. My function would be something like:

function getAge(): Promise<number> {
  return new Promise((resolve) => {
  resolve(42)
  })
}

My variable with default values would be:

let user: { name: string, age: number } = { name: "", age: 0 }

I've tried using the ReturnType<>, however I can only seem to get the return type Promise<number>, when I just want number returned.

like image 293
Stephan Olsen Avatar asked Jan 26 '23 00:01

Stephan Olsen


1 Answers

You can use a conditional type to extract the value type of a promise:

function getAge(): Promise<{ name: string, age: number }> {
  return new Promise((resolve) => {
  resolve({ name: "", age: 42 })
  })
}

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

let user: UnboxPromise<ReturnType<typeof getAge>> = { name: "", age: 0 }

Read more about conditional types here

like image 68
Titian Cernicova-Dragomir Avatar answered Feb 03 '23 21:02

Titian Cernicova-Dragomir