Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript promise generic type

I've a sample Promise function like below. On success I return a number and on false I return string. The compiler is complaining to specify some kind of generic type to the promise. In this case what type I've to specify? Do I've to specify like Promise<number> or Promise<number | string>?

function test(arg: string): Promise {     return new Promise((resolve, reject) => {         if (arg === "a") {             resolve(1);         } else {             reject("1");         }     }); } 
like image 586
VJAI Avatar asked Dec 10 '16 18:12

VJAI


People also ask

What is the 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.

How do you define a generic type in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.

How do you pass a generic type as parameter TypeScript?

Assigning Generic ParametersBy passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.

Does TypeScript support generics?

TypeScript supports generic classes. The generic type parameter is specified in angle brackets after the name of the class. A generic class can have generic fields (member variables) or methods.


1 Answers

The generic type of the Promise should correspond to the non-error return-type of the function. The error is implicitly of type any and is not specified in the Promise generic type.

So for example:

function test(arg: string): Promise<number> {     return new Promise<number>((resolve, reject) => {         if (arg === "a") {             resolve(1);         } else {             reject("1");         }     }); } 
like image 136
Dave Templin Avatar answered Sep 19 '22 12:09

Dave Templin