Sergi Juanati
Sergi Juanati

Reputation: 1436

Types in object destructing from async function return in Typescript

Given a function that returns an object promise with a boolean & string:

const test = () => {
   return new Promise(async (resolve) => {
       resolve({ result: false, error: 'This is an error' });
   })
}

I try to destruct these couple of values into constants:

const { result, error } = await test();

However, I always get these Typescript errors:

Property 'result' does not exist on type 'unknown'.ts(2339)
Property 'error' does not exist on type 'unknown'.ts(2339)

I've tried all kinds of combinations, but the only one working is adding the 'any' type, which I believe we should always avoid.

Any idea to define the right types without getting error?

Upvotes: 1

Views: 2599

Answers (2)

Adrian Brand
Adrian Brand

Reputation: 21658

Give your response a type

return new Promise<{ result: boolean, error: string }>((resolve) => {})

Upvotes: 2

mbdavis
mbdavis

Reputation: 4020

Here you should add the type as the generic parameter to the promise - i.e new Promise<MyType>(...) Example:

type MyPromiseResult = { result: boolean, error: string };

const test = () => {
   return new Promise<MyPromiseResult>((resolve) => {
       resolve({ result: false, error: 'This is an error' });
   })
}

async function doThing() {
  const { result, error } = await test();
  type ResultType = typeof result; // boolean
  type ErrorType = typeof error; // string
}

Upvotes: 3

Related Questions