I need assistance with adding type-safe return to a general function created by a previous developer. Here is the current syntax:
export function to(promise:Promise<any>) {
return promise
.then(data => [null, data])
.catch(err => [err, null]);
}
This function simply takes in a promise and returns a new promise with an output type of a tuple
[Error|null, <The First Promise's Return Type>|null]
. This means that the first value will be an error if there is one (otherwise null
), and the second value will be the result of the initial promise (otherwise null
). Usage example:
const [ err, result ] = await to(/*<API Call>*/);
if (err) {
setError(err);
// ...
} else if (result) {
processApiResult(result);
// ...
}
Currently, I am aware that there is an issue ((T|null)[]
should not represent "an array of either of those types", but rather "a tuple of those types with a specific order"), but I have been struggling to find a solution.
export function to<T>(promise:Promise<T>):Promise<(T|null)[]|[Error, null]> {
return promise
.then(data => [null, data])
.catch(err => [err as Error, null]);
}
const [ err, result ] = await to(api.changePassword(username, password));
// const error : string | Error | null
// const result : string | null
The expected type for the first parameter should be Error | null
(not | string
), while the second parameter is correctly defined as string | null
.