Skip to content

Instantly share code, notes, and snippets.

@bennycode
Last active August 29, 2023 13:54
Show Gist options
  • Save bennycode/92c29dfcbb3d1fab99b8bb3fbbcb6423 to your computer and use it in GitHub Desktop.
Save bennycode/92c29dfcbb3d1fab99b8bb3fbbcb6423 to your computer and use it in GitHub Desktop.
Better error handling with unknown type in TypeScript
const hasErrorCode = (error: unknown): error is { code: string } => {
return !!error && typeof error === 'object' && 'code' in error && typeof error.code === 'string';
};
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