Narrowing Return Types with TypeScript
Here we have a throwError
function that takes in a message
and, as the name suggests, throws an error. It also has been given a return type of undefined
, indicating that the function returns undefined
:
const throwError = (message: string): undefined => { throw new Error(message);}
Transcript
00:00 In this exercise, we have a throwError function. This throwError function takes in a message here and throws the error. It's also been given a return type of undefined here, so this function kind of returns undefined, or at least this is what this is saying. And we have a handleSearchParams function here.
00:18 The handleSearchParams takes in a params, which is id of string, or it might be an id of string. And then we're saying const id equals params id, or throw an error, no id provided. And what we're doing here is inside this id,
00:34 this id is now string or undefined inside this handleSearchParams function. And we're trying to get this id into a spot where it's actually narrowed down to string. Because if you think about it, we've got one branch here, which is the params.id, and if params.id is defined, then it's going to be string,
00:53 so id will end up being string. Great. If it's not defined, or if it's a falsy value, which is what this or symbol is doing, then we're going to throw an error. We're going to run this piece of code, throw a new error message, and it's going to throw an error with no id provided.
01:07 So in theory, this id here should be just string instead of string or undefined. So your job actually is not to change any of the code inside handleSearchParams, it's to change some code inside throwError, inside this function here. And see what you can come up with,
01:24 and see if you can find a better type definition for throwError, which actually makes this happen. Good luck.