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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With