Unions and Narrowing 28 exercises
Problem

Narrowing in Different Scopes

Here we have a function findUsersByName that takes two arguments: a searchParams object which could contain a name string, and a users array of objects, each having id and name properties.

Inside the function, we check if searchParams.name exists. If it does, we return a filtered arr

Loading exercise

Transcript

00:00 In this exercise, we have a function called findUsersByName. We have a search params object being passed in, where we have some search params which might contain a name string. Next, we have some users, which is an array of objects which each contain ID and name. We're passing both of those into the same function.

00:19 We're first of all checking if there is a searchparams.name, and if there is, we're returning users.filter, and then inside that filter, we're checking if the username includes searchparams.name, and then if we don't get a searchparams.name, we're just returning the users. Inside our test below, we've got some findUsersByName,

00:38 we're checking for the name Bob, and we're expecting the users to be filtered out into ID1 and name Bob. Now, there's an issue here, and the issue is inside our filter function. Username.includesSearchparams.name is erroring for us. It's saying argument of type string or undefined

00:58 is not assignable to parameter of type string. That's really weird, because we're narrowing searchparams.name here, why wouldn't it also be narrowed here? That's interesting. So your job is to try to figure out why this is happening and see if you can kind of work with TypeScript a little bit,

01:17 find another way to write this code where this error goes away, but the behavior is preserved. So don't change any of the type definitions up here, we're just changing the stuff inside the function body. Good luck.