Unions and Narrowing 29 exercises
Problem

Reusable Type Guards

Consider the following code:


const joinNames = (value: unknown) => {
if (Array.isArray(value) && value.every((item) => typeof item === "string")) {
return value.join(" ");
}
throw new Error("Parsing error!");
};
const createSections = (value: unknown) => {
if (Array.i

Loading exercise

Transcript

00:00 Let's imagine that we have 2 functions that do very, very similar things. We have join names here, which takes in a value which is unknown. This could be a value coming from anywhere, coming from search params, coming from user inputs. And it checks to see if it's an array, first of all, then it checks to see if every single item is a string

00:19 inside them. And then if this works, then it joins them all together. We also have something that has pretty much the same logic in createSections, which takes in a value of unknown, does the same check, array.isArray, checks every single item, and then maps over it, and basically maps it with a section. So reformats the text. We've got some

00:38 tests making sure they behave as expected and there's no errors in this file. But there's a bit of duplication happening here. We can see it just here. This duplication is a little bit awkward because we've got 2 pieces of logic that look exactly the same. Why not create a reusable type

00:55 guard to basically grab that logic and just put it in a function somewhere so we can reuse it hundreds of times. That's your job, is to make sure everything keeps passing here, but we refactor it out to its own function to see if we can just reduce some of this duplication. Good luck!