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"); } }); }
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.
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.
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.
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.
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"); } }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With