0👍
- Exceptions in JavaScript are untyped, and TypeScript cannot use type-checked
catch
blocks (nor.catch
promise methods).- Indeed, it’s perfectly valid to do
throw null;
orthrow "Hello, world";
in JavaScript. - …and TypeScript code must correctly handle those situations.
- Indeed, it’s perfectly valid to do
…so you need to handle all of those cases in TS. To do this, you’ll need a type-guard function, like so:
interface MyError extends Error {
readonly response: MyResponse;
}
interface MyResponse {
readonly data: MyData;
}
interface MyData {
readonly message: string;
}
function isMyError( x: unknown ): x is MyError {
const whatIf = x as MyError;
return (
typeof whatIf?.response?.data?.message === 'string'
);
}
Then change your code to use async/await
with try/catch
instead of old-style Promise .then().catch
:
try {
await yourPromise();
loginError.value = false;
}
catch( err: unknown ) {
loginError.value = true;
if( isMyError( err ) ) {
console.error( "MyError: %s", err.response.data.message );
}
else {
console.error( "Unexpected error: %o", err );
}
}
Source:stackexchange.com