By default, promise rejection returns type void.
Promise.reject(reason?: any) => void
Imagine a scenario where we have a getUser function that retrieves a User object to be passed to a login function. We use a Promise that resolves when the user is found and rejects when no user is found or an error occurs.
// getUser returns an object or void
getUser(): Promise<object|void> {
return new Promise((resolve, reject) => {
// user is found
resolve({ user: user });
// user is not found or error
reject();
});
}
login(): void {
this.getUser()
.then((result: object) => {
// get user here to send back
this.res.status(200).json({
user: result['user']
});
})
.catch(() => {
// don't need to receive data here
this.res.status(500).json({
error: 'No login'
});
});
}
Should the return type be explicitly set as VOID in the function signature?
getUser(): Promise<object|void>
Or is it sufficient to only specify the return type as object?
getUser(): Promise<object>