Designing Your Types 11 exercises

Constrain Strings to Match a Pattern with Template Literal Types

In order to specify that AbsoluteRoute is a string that begins with a forward slash, we'll use a template literal type.

Similar to how template literals in JavaScript allow you to interpolate variables into strings, template literal types in TypeScript allow you to interpolate other types into s

Loading solution


00:00 Okay, the solution for this is so cool. You have template literal types in TypeScript, which are kind of like literal types or literal strings on steroids. Instead of doing something like this, where we say forward slash home or forward slash about or forward slash contact, we want to basically say, okay,

00:19 any string that starts with a forward slash is valid. This means then that you can use this backtick syntax. And these backticks, basically, unlike literal types, they let you pass in other string types to a template literal. So in here, we could say type A, for instance,

00:37 or let's say we put another template literal inside it. So we say A in there. And now what you get is you can pass something with a forward slash and an A. So it would be forward slash A. We can pass in a literal or a union here. So we can say A or B and bam, we get A and B here with the forward slash in front.

00:57 This is really nice, but it's not quite the solution that we want. The solution that we want is to be able to pass any string into this slot. And I wonder how we would do that. We just pass in a string there. Look at that. And now any string that starts with,

01:15 and including this as well. So we like, first of all, it lets us do just a string with no length or any string that starts with a backslash is absolutely fine. So this means you can be really expressive with the way that you handle all of your different string types in TypeScript. And for instance,

01:33 if it needed to end with a backslash as well, then all of these would be incorrect. And so you end up with like, this would be kind of weird, just having like two backslashes. So maybe we could change this and have a union and just allow for the case where you have just sort of one slash here. And so this is kind of like almost RegEx in TypeScript for different strings.

01:52 And if we add in the forward slashes there, then bam, we're good to go. So template literals, this is a really, really cool feature that you can go very, very, very deep on, but is just useful if you have a certain sort of set of strings that you want to make sure work. Very, very nice.