Conditional Types and Infer 10 exercises
solution

Pattern Matching on Template Literals with Infer

There are two solutions to extracting the last names from the template literals in the Names tuple:


type Names = [
"Matt Pocock",
"Jimi Hendrix",
"Eric Clapton",
"John Mayer",
"BB King"
]

Solution 1: Using S.Split

We can use S.Split to split the template literal by s

Loading solution

Transcript

0:00 There's a solution here that you might have spotted actually and you may even have used, but it's not quite the thing I wanted to cover.

0:07 GetSurname here, you can ignore this little bit of syntax for now, but we now understand that S.Split, from one of the lessons before, we can split it by the space and return the second element. This means that you would basically split this by the space, return the thing that was second, which is cool.

0:28 The solution I wanted you to find was this one, which is GetSurname here, we can say, "T extends." Then we open up a template literal. Inside this template literal, we can add these infers. We can say, "infer First" and then space and then "infer Last" and then just return the last name.

0:48 I really love this sort of pattern matching syntax because it allows us to declare these capture groups, which we're grabbing values from. This means that we can just grab that Last out there. I think this actually reads a little bit better than this solution here. This one's a little bit heavier, but this allows us to say, "infer First infer Last," which gives us a bit more semantic meaning.

1:11 This means that this thing that we're extracting here allows us to capture the thing that we're pattern matching for inside the string. This first infer is actually not needed. We could just turn this into string if we wanted to, but I wanted to show that you can have multiple of these stacked next to each other.