I am wondering why Promise<T> doesn't take two params, like so: Promise<T1,T2>.
for example:
new Promise(function(resolve,reject){
...
err ? reject(err) : resolve(val);
});
=> how can I tell the consumer of the promise about the type of both err and val?
I would expect T1 to be the Error type and T2 to be the type of val.
Why doesn't Promise take two type parameters? Because it officially takes only one, I assume the parameter is the type of the value passed to resolve()? Is there only one parameter because we expect an Error type to always be passed to reject()?
In further detail, we can pass a string to reject:
new Promise(function(resolve,reject){
let err = 'just a string, not an object';
let val = {foo:'bar'};
err ? reject(err) : resolve(val);
});
Note that we could coerce the error to a certain type, like so:
return function(){
return Promise.resolve('whatever')
.catch(function(){
return Promise.reject('always a string');
});
}
so it's not really true that the error could always be anything? Seems like we know the error will be a string in the above example...
Because the reject parameter is typed as
(reason? : any) => voidyou can't specify the type of the reject reason.As to why it is typed this way, the most likely the main reason is the one @Titian gave. Anything inside the code that throws something would be caught by the promise and propagated up the promise chain as the error. Giving it a type might make the user think it's supposed to expect only a specific type while it could really be anything.
Mainly for situations like this one: