The Weird Parts of TypeScript 13 exercises
Problem

Annotating the Errors Thrown by a Function

In TypeScript, there's an interesting problem of annotating the errors that a function can throw. This is particularly interesting for those coming from a Java background.

Consider a function named getUserFromLocalStorage that takes an id and returns a user object from localStorage:



Loading exercise

Transcript

00:00 There's an interesting problem in TypeScript which if you've come from, let's say, a Java background, you might be interested to learn. And that is annotating the errors that a function throws. Let's say we have a getUserFromLocalStorage function. This can either throw in really one or two ways. It can either produce a syntax error where we're saying inside our JSON.parse,

00:19 the thing that we get from local storage, that might be incorrectly formatted or it might have been altered by some other program. So we might get a syntax error out of that. Or local storage might not be permitted on the browser that we're using. So we might get a DOM exception to an abnormal event from the DOM. And when it would be great if we could say, okay, getUserFromLocal

00:39 Storage, it's either going to return or going to throw one of those errors. Now what we can do is we can say const user equals get local. When we call this, when we have a try catch around it,

00:54 this e is going to be typed as unknown. Now it would be really great if we could make e typed as these possible errors up here. Your job is to give this a go and work out based on your research if it's even possible. Good luck.