TypeScript: Type The argument for a parameter of type "R" cannot be taken out of use

With TypeScript 1.6 and native es6 Promises, I get an error when I use Promise.all([]) with two different return types. For instance:

 let onePromise:Promise<string[]> = getOne(); let twoPromise:Promise<MyObject> = getTwo(); Promise.all([onePromise, twoPromise]) .then((values:[string[], MyObject]) => { let one:string[] = values[0]; let two:MyObject = values[1]; // do stuff }); 

In this example, I get an error message in the Promise.all line from the TypeScript error TS2453: The type argument for type parameter 'R' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'string[]' is not a valid type argument because it is not a supertype of candidate 'MyObject'. Property 'length' is missing in type 'MyObject'. error TS2453: The type argument for type parameter 'R' cannot be inferred from the usage. Consider specifying the type arguments explicitly. Type argument candidate 'string[]' is not a valid type argument because it is not a supertype of candidate 'MyObject'. Property 'length' is missing in type 'MyObject'.

I actually have another example of this, where the second and third sentences of the error are different from each other, but the first sentence is the same. So basically I'm wondering what the syntax is for “explicitly specifying type arguments”. I don't seem to understand. The code is working fine, but I would like to get rid of this transpiler warning.

+5
source share
2 answers

Here's a workaround:

 let onePromise:Promise<string[]> = getOne(); let twoPromise:Promise<MyObject> = getTwo(); Promise.all<string[] | MyObject>([onePromise, twoPromise]) .then((values:[string[], MyObject]) => { let one:string[] = values[0]; let two:MyObject = values[1]; // do stuff }); 

A vertical bar is used to indicate a value, which can be one of several types.

+3
source

I only know about this workaround:

 ///<reference path="typings/es6-promise/es6-promise.d.ts" /> class MyObject {} let onePromise:Promise<string[]> = null; let twoPromise:Promise<MyObject> = null; Promise.all([onePromise, twoPromise]) .then((data:any) => { let values:[string[],MyObject] = data; let one = values[0]; let two = values[1]; // do stuff }); 
+1
source

Source: https://habr.com/ru/post/1236927/


All Articles