In Typescript, exceptions can be a bit weird. This is especially true if you’re writing library code or a VSCode plugin. Because almost surely you’ll want to output nice and custom error messages to the end user.
Typescript doesn’t allow for a try/catch block to catch type errors, like it would for runtime errors.
So the question becomes;
How do you handle exceptions in a typesafe way?
Let’s see if I can’t answer that today!
Type Predicate functions
When working on large code-bases you will almost surely be faced with working with:
- Errors
- Json decoded data (
any
by default) - Third party APIs (
unknown
by default)
Type predicate functions are a way to make working with the above slightly more convenient.
Let’s imagine the following predicate function:
const isErrorWithCode = (err: unknown): err is Error & { code: unknown } => {
return err instanceof Error && 'code' in err;
}
This method, isErrorWithCode
takes an input and ensures that it is of type Error
and it has the code
attribute.
This method, we can actually use in a try/catch block! So we could end up having a try/catch looking as so:
try {
// do thing
} catch (err) {
if (isErrorWithCode(err) && err.code === 'ENOENT') {
// not found
}
}
Using the function as such will actually bubble up the error providing good user feedback while ensuring a consistent reliable behaviour.
There it is! 🎯
Today was just a brief little helper that I hope can help you deal with some of those pesky Type errors that we see from exceptions .