Techniques for Coercing an Unknown Type
As mentioned, there are several ways to solve this problem.
Use Any Type
One way to solve this challenge is to type e
in the catch
as any
:
} catch (e: any) {
return e.message;
}
We can use any
because we're pretty confident that the error is going to be an error.
Transcript
0:00 This one has several solutions. Here, we're just doing it as an any. We can use any in this position because we're pretty confident that the error is going to be an error. It's not the ideal solution because this e here, we lose all autocomplete on it and it's very, very easy to do something like this and not notice it, and have a typo here and we don't even realize it, which would make the test fail.
0:28 Any, it's fine if you want to use it and it's very, very low impact here. It's just going to be within this block. If you really want to do it right, then I wouldn't suggest doing any.
0:40 The next way to do it is pretty similar, I would say, is you've got e as error inside here. E is unknown here. Then you coerce it to say, "e is an error," and then you extract the message from it. Here, we're not saying it's any here. We do get things from it. We get message, we get name, we get stack. If I add a typo here, then it's going to alert me. This is a little bit better.
1:06 Technically, if this block was longer and more complicated, which yours in production are usually going to be, then e might not be an error. You might end up with someone accidentally saying, "Throw failure," in which case, you're going to return undefined here. This is not the perfect solution either, but it's better than the previous one.
1:28 This one is a better solution. What we're doing here is we're saying e is unknown in this position, but we're checking e and checking if it's an instance of error here. This is like the typo that we saw earlier. That instance of is then going to whittle down what that error can be. We've got e.message, e.name, e.stack.
1:52 Unlike the previous ones, we are actually checking at runtime what that type is and doing something based off that. We're not casting it using the as that we saw before, and we're not blanketing over it with any, which we also had before.
2:07 This is my recommended solution. It's also pretty tight. If you get something that isn't an error, then it's going to fall down into this block, and you might need to do something else with it. This is probably the safest approach. Depending on the constraints of your code base, your time constraints, and how much you care about avoiding anys, then you might want to prefer one of the other solutions.