Beginner's TypeScript #13

nhannguyendevjs

Nhan Nguyen

Posted on January 1, 2024

Beginner's TypeScript #13

Image description

Typing Errors in a Try-Catch

Take a look at this try-catch demo:

const tryCatchDemo = (state: "fail" | "succeed") => {
  try {
    if (state === "fail") {
      throw new Error("Failure!");
    }
  } catch (e) {
    return e.message;
  }
};
Enter fullscreen mode Exit fullscreen mode

TypeScript gives us an error on e.message that the object is of type unknown.

We will figure out how to coerce the unknown type into one where we know what it is.

🌟 Solutions:

We have several ways to solve this problem.

1️⃣ Use Any Type:

One way to solve this challenge is to type e in the catch as any:

} catch (e: any) {
  return e.message;
}
Enter fullscreen mode Exit fullscreen mode

We can use any because we are pretty confident that the error will be an error.

What makes this solution not ideal is that we lose autocomplete on the e. This makes it easy to end up with typos that can cause issues later.

This is not a good solution.

2️⃣ Coerce as Error:

A slightly better solution would be to coerce e to be an Error, and return the message:

} catch (e) {
  return (e as Error).message;
}
Enter fullscreen mode Exit fullscreen mode

Here e is still unknown when we enter the catch, but using as coerces it to an Error, and we get our autocomplete as expected.

This solution is about as unsafe as the one above - we are not checking if e is an Error. We are casting it as an error.

3️⃣ Check with instanceof:

This solution is pretty similar to the last, except this time we'll use instanceof to see if e is an Error:

} catch (e) {
  if (e instanceof Error) {
    return e.message;
  }
}
Enter fullscreen mode Exit fullscreen mode

Unlike previous solutions. This time we are checking e at runtime to whittle down what it could be.

We are not blanketing it with the any type, and we are also not casting it to something else either.

This is the best solution because it is the safest.


I hope you found it useful. Thanks for reading. 🙏

Let's get connected! You can find me on:

💖 💪 🙅 🚩
nhannguyendevjs
Nhan Nguyen

Posted on January 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Beginner's TypeScript #tips
programming Beginner's TypeScript #tips

January 24, 2024

Beginner's TypeScript #27
programming Beginner's TypeScript #27

January 19, 2024

Beginner's TypeScript #26
programming Beginner's TypeScript #26

January 18, 2024

Beginner's TypeScript #25
programming Beginner's TypeScript #25

January 17, 2024