Last active
August 29, 2023 13:54
-
-
Save bennycode/92c29dfcbb3d1fab99b8bb3fbbcb6423 to your computer and use it in GitHub Desktop.
Better error handling with unknown type in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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