Template Literals 7 exercises
solution

Template Literal with Strings

The template literal syntax in TypeScript is similar to the JavaScript syntax, except you can put types inside of it.

Here's how we would format strings that begin with a slash:


type Route = `/${string}`

Experiment with @ts-expect-error

Note that we are using the `@ts-expect-err

Loading solution

Transcript

0:00 The way to do this is by using a template literal bit of syntax here. We're using this little backtick here to indicate that this is a string of a certain value. We're using this dollar sign syntax to add values to it.

0:18 This is pretty similar to the syntax that you're used to in JavaScript except that you can put types inside here. This Route now represents any route that starts with a slash here. If we take away this, @ts-expect-errors, which this is an assertion saying that the next line will error.

0:37 Then here, it's saying, it's not assignable to parameter of type, forward slash string. This string can be zero length of course. This can just be a thing on its own or it can be a thing with multiple of these. If it doesn't have one of these at the start, then it's going to yell at us.

0:55 This is interesting. This lets us be specific with the types of strings that you can pass in. As we'll see, this whole section is going to be on template literals, because they're powerful in typeScript.