LEARNING JOURNAL

I created this learning journal to practice writting and to help me learn by writting everything down. Source code here

12/29/2023

Practical use of unknown in TypeScript

The function doSomethingRisky can either return a string, throw an error, or throw a string. The problem here is it can throw a string. You should make your function throw something throwable, like an Error. But if it is not your function, like something in the node_modules folder, you cannot control what it throws. So you need to handle it.

The way you handle it is illustrated in the function doSomething. First, your cast whatever the function throws to unknown, because you really don't know what it is. Then, you check if it is an Error, you console.log its message. Then, you check if it is a string, you console.log it. Finally, if it still not an Error or a string, you run out of gueses and really don't know what it is, so you console.log it.