Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript type definition for promise.reject

The following code is correct in terms of the type that is returned, because then always return the promise array.

Promise.resolve(['one', 'two'])
.then( arr =>
{
  if( arr.indexOf('three') === -1 )
    return Promise.reject( new Error('Where is three?') );

  return Promise.resolve(arr);
})
.catch( err =>
{
  console.log(err); // Error: where is three?
})

TypeScript throw error:

The type argument for type parameter 'TResult' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'void' is not a valid type argument because it is not a supertype of candidate 'string[]'.

But in reality, then never will return void.

I can explicitly specify type .then<Promise<any>>, but it's more like a workaround, not the right solution.

How to write this right?

like image 772
ktretyak Avatar asked Sep 08 '16 03:09

ktretyak


People also ask

How do you define a type of Promise in TypeScript?

In TypeScript, promise type takes an inner function, which further accepts resolve and rejects as parameters. Promise accepts a callback function as parameters, and in turn, the callback function accepts two other parameters, resolve and reject. If the condition is true, then resolve is returned; else, returns reject.

What is return type of Promise reject?

The Promise. reject() method returns a Promise object that is rejected with a given reason.

How do you reject a Promise?

You can reject a promise with any value, not just an error object. const p = Promise. reject(42); return p.

What is the type of resolve and reject in Promise?

A promise's state can be pending , fulfilled or rejected . A promise that is either resolved or rejected is called settled .


1 Answers

You should not return Promise.resolve and Promise.reject inside a promise chain. The resolve should be driven by simple return and reject should be driven by an explicit throw new Error.

Promise.resolve(['one', 'two'])
.then( arr =>
{
  if( arr.indexOf('three') === -1 )
    throw new Error('Where is three?');

  return arr;
})
.catch( err =>
{
  console.log(err); // Error: where is three?
})

More

More on promise chaining https://basarat.gitbooks.io/typescript/content/docs/promise.html

like image 62
basarat Avatar answered Sep 26 '22 07:09

basarat