I am using an async function to call an existing promise-based API which rejects the promise with a typed error.
You could mock this behavior like this:
interface ApiError {
code: number;
error: string;
}
function api(): Promise<any> {
return new Promise((resolve, reject) => {
reject({ code: 123, error: "Error!" });
});
}
Now with promises, I can annotate the error type to ApiError:
api().catch((error: ApiError) => console.log(error.code, error.message))
But when using async if I try to annotate the error type in try ... catch():
async function test() {
try {
return await api();
} catch (error: ApiError) {
console.log("error", error);
}
}
It compiles with error:
Catch clause variable cannot have a type annotation.
How, then, do I know what kind of error I'm expecting? Do I need to write an assertion in the catch() block? Is that a bug/incomplete feature of async?