Skip to content

Instantly share code, notes, and snippets.

Last active Nov 29, 2022
What would you like to do?
Better error handling with unknown type in TypeScript
const hasErrorCode = (error: unknown): error is { code: number } => {
return !!error && typeof error === 'object' && 'code' in error;
try {
throw {code: 72};
} catch (error: unknown) {
if (hasErrorCode(error)) {
console.error(`Failed with error code "${error.code}".`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment