TypeScript type definition for prom.reject

The following code is correct in terms of return type, because then always returns an array of promises.

 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:

A type argument for a parameter of type "TResult" cannot be taken out of use. Consider explicitly type arguments. The type argument "void" is not a valid type argument because it is not a supertype of the candidate "string []".

But actually then will never return void .

I can explicitly specify the type .then<Promise<any>> , but this is more like a workaround, rather than a correct solution.

How to write it right?

+6
source share
2 answers

You should not return Promise.resolve and Promise.reject within the promise chain. resolve should be controlled by a simple return, and reject should be controlled 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 details

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

+6
source

Typescript complains about the difference in return type between the return value of Promise.reject ( Promise<void> ) and your value of Promise.resolve ( Promise<string[]> ).

Making a call then as .then<Promise<void | string[]>> .then<Promise<void | string[]>> will allow the compiler to find out the type of union to return.

as @basarat notes, you should just throw an error instead of using Promise.reject (which will be passed to any catch handler).

+3
source

All Articles