Designing Your Types 11 exercises
Problem

Template Literal Types in TypeScript

Here we have a route typed as AbsoluteRoute:


type AbsoluteRoute = string;
const goToRoute = (route: AbsoluteRoute) => {
// ...
};

We're expecting that the AbsoluteRoute will represent any string that has a forward slash at the start of it. For example, we'd expect the followin

Loading exercise

Transcript

00:00 In this exercise, we're going to look at a really interesting property of Types in TypeScript, and we're going to start talking about template literal types. We have a root here that's called an absolute root, and we're expecting absolute root to basically represent anything that has

00:14 a forward slash at the start of it. So here we have home, contact, and about, each with a forward slash at the start, and we have then somewhere down the bottom which doesn't have a forward slash at the start. So we're expecting somewhere to error, but in fact it's not. It's just allowing

00:30 us to pass somewhere in when we actually just want any string with a forward slash at the start. Your job is to work out how to type absolute root, because string is obviously a little bit too wide, and for this we're going to need a template literal type. That is pretty used like pretty

00:48 like syntactically similar to the template literals that you've already seen in JavaScript, so your job is to look at the link below, see what you can find out about template literal types, see if you can get this type working. Good luck!