Template Literal Type

Pro Members Only

This lesson is available if you have an active subscription.

Alternatively, some member might be able to gift it to you.

If you already have a subscription, you can sign in.

Professional TypeScript Masterclass Lessons

1.Introduction
free
⏱️ 1:54
2.Setup
free
⏱️ 5:44
3.Primitive Types
free
⏱️ 1:42
4.Instance Types
free
⏱️ 1:52
5.Arrays And Tuples
free
⏱️ 1:38
6.Objects
free
⏱️ 1:33
7.const declarations
free
⏱️ 1:03
8.Function Types
free
⏱️ 1:57
9.Structural Typing
free
⏱️ 2:10
10.Classes in TypeScript
free
⏱️ 1:48
11.Target Compiler Option
free
⏱️ 2:37
12.Generics
⏱️ 3:02
13.Special Types any And unknown
⏱️ 2:00
14.JavaScript to TypeScript
⏱️ 1:32
15.Frontend Projects
⏱️ 3:49
16.Type Assertions
⏱️ 2:15
17.Type Casting
⏱️ 1:16
18.Modules
⏱️ 1:55
19.Type Declarations
⏱️ 4:25
20.Creating NPM packages
⏱️ 3:20
21.Async Await
⏱️ 3:05
22.Running in NodeJS
⏱️ 1:40
23.Lexical this
⏱️ 2:34
24.readonly Modifier
⏱️ 1:59
25.Union Types
⏱️ 2:57
26.Literal Types
⏱️ 2:58
27.Type Narrowing
⏱️ 4:19
28.Discriminated Unions
⏱️ 3:29
29.Class Parameter Properties
⏱️ 1:02
30.Strict Compiler Option
⏱️ 6:18
31.null vs undefined
⏱️ 4:19
32.Intersection Types
⏱️ 2:03
33.Optional Modifier
⏱️ 2:47
34.Non Null Assertion Operator
⏱️ 3:40
35.Interfaces
⏱️ 2:28
36.Interface Declaration Merging
⏱️ 1:01
37.Types vs Interfaces
⏱️ 2:16
38.never Type
⏱️ 3:00
39.implements Keyword
⏱️ 1:25
40.Definite Assignment Assertion
⏱️ 2:31
41.User Defined Type Guards
⏱️ 2:02
42.Assertion Functions
⏱️ 3:42
43.Function Overloading
⏱️ 4:15
44.Call Signatures
⏱️ 2:53
45.Abstract Classes
⏱️ 1:53
46.Index Signatures
⏱️ 3:08
47.Readonly Arrays and Tuples
⏱️ 2:58
48.Double Assertions
⏱️ 2:20
49.const Assertions
⏱️ 3:55
50.this Parameter
⏱️ 2:33
51.Generic Constraints
⏱️ 2:43
52.typeof Type Operator
⏱️ 2:12
53.Lookup Types
⏱️ 3:12
54.keyof Type Operator
⏱️ 3:55
55.Conditional Types
⏱️ 4:39
56.Contitional Types with Unions and never
⏱️ 3:32
57.infer Keyword and `ReturnType<T>`
⏱️ 3:47
58.Mapped Types
⏱️ 2:48
59.Mapped Type Modifiers
⏱️ 3:37
60.Template Literal Type
⏱️ 4:28
61.Partial<T>
⏱️ 1:27
62.Required<T>
⏱️ 1:36
63.Readonly<T>
⏱️ 1:34
64.Record<K, T>
⏱️ 4:05
65.Project References
⏱️ 4:18
66.undefined vs. optional
⏱️ 2:48
67.satisfies Operator
⏱️ 2:42
68.PropertyKey Type
⏱️ 0:57
69.ThisType<T>
⏱️ 4:11
70.Awaited<T>
⏱️ 4:12
71.String Manipulation Types
⏱️ 3:36
72.Mapped Types as Clauses
⏱️ 4:01
73.Union vs Intersection Mental Model
⏱️ 3:36
74.Enums are Bad
⏱️ 8:11

Template Literal Type

Subscription Required

You must have an active subscription to access this content.
If you already have a subscription, you can sign in.

JavaScript Recap

let jsStringLiteral;
jsStringLiteral = 'hello';
jsStringLiteral = "whatever";

let jsTemplateLiteral;
jsTemplateLiteral = `Example: ${jsStringLiteral}`; // Example: whatever
jsTemplateLiteral = `Example: ${3.14}`; // Example: 3.14

TypeScript Template Literal Types

let str: string;
str = 'whatever you want';

let strLiteral: 'hello';
strLiteral = 'hello';
strLiteral = 'anything else is an error'; // Error: not 'hello'

let templateLiteral: `Example: ${string}`;
templateLiteral = 'Example: hello';
templateLiteral = 'Example: world';
templateLiteral = 'without a Example prefix'; // Error: not `Example: ${string}`

Example CSS in JS

type CSSValue =
// implies px
| number
// number + px|em|rem
| `${number}px`
| `${number}em`
| `${number}rem`

function size(input: CSSValue) {
return typeof input == 'number' ? input + 'px' : input;
}

size(123);
size('123px');
size('12em');
size('12ez'); // Error

Example Design System

type Size = 'small' | 'medium' | 'large';
type Color = 'primary' | 'secondary';
type Style = `${Size}-${Color}`;

/**
* @param style is a combination of
* Size: 'small' or 'medium' or 'large'
* Color: 'primary' or 'secondary'
* e.g. 'small-secondary'
*/
function applyStyle(style: Style) {
// ...
}

applyStyle('small-primary');
applyStyle('large-secondary');
applyStyle('medim-primary'); // Error
javascript
typescript
react
playwright

Enjoy free content straight from your inbox 💌

No spam, unsubscribe at any time.

Transcript

00:00

Traditionally, there were only two ways of representing a string Within JavaScript, you could use single coats or you could use double coats. In modern JavaScript, there is a third way known as JavaScript template literals. And this is done by using bad text. And the special thing about them is that you can add any JavaScript expression as a part of your string by skipping into the expression mode, by using the dollar sign, followed by curly brackets. For example, we can bring in a local variable called JS string literal, which in our case is pointing to the string, whatever, or we can even use any other value like the

00:34

number 3.14. There is of course more to JavaScript template digitals, but all that you need to know for this lesson on TypeScript template digital types is that they start with back takes. And within the dollar curly brackets you can use any JavaScript value. Now let's talk about TypeScript. Of course, there are a number of types within TypeScript to represent various JavaScript on time values. For example, here we have the type penetration called string, which will accept literally any string that you can throw at it. But in addition to general types like string and number, TypeScript also supports what are known

01:08

as literal types. For example, you can put the literal type called the string. Hello. And now the only string that this particular variable will accept is the string. Hello. Anything else will result in a compile time error. And that brings us to the latest feature of types scraped, which is template literal types. Here we have a template literal type where we are saying that it must be a string that contains the prefix example colon space, followed by any other string value. This means that something like example, hello will be perfectly fine.

01:40

Example world will be perfectly fine, but anything else that does not start with example will result in a compiled time error. Now just like in a JavaScript template, literal, you can put any JavaScript value. You can put any TypeScript type within the TypeScript template little. Here we are using the type string. So in this particular code demo, you are essentially using the TypeScript template little to ensure that all strings assigned to this particular variable start with the example prefix, but that's not particularly useful. So let's jump into some real world use cases

02:14

for this particular feature. Now, it's common for CSS values to be represented by either a number, in which case it is implied that it's a pixel value, or alternatively, with a full string that contains the number followed by the unit of the number, which let's just assume can be PX or M or rems. And just as a demo, here's a function that accepts the CSS value. We check if the input is a number and if it is, we append px. Otherwise, we use the value as is trusting the user to have provided a valid unit. However, this trust is something

02:46

that can be broken quite easily. The user can easily pass in a number or a PX or an M or fudge it up and pass an ex, and it would be great if we could catch it at compile Time. Essentially what this comment for string is saying is that it must be something that starts off with a number and ends with either a PX or an M or a rem. And this is something that we can represent quite easily with template literal types. And with that, any misuses are easily caught at compile time.

03:19

Now let's look at another example. Here we have a function called apply style that expects the style to be passed in as a string combination of some size, which can either be a small, medium or large, along with some color, which can either be primary or secondary. This means that something like small primary will be fine, large secondary will be fine, but if you mistype medium in medium primary, we want to compile time error. Now we can do that quite easily with template literal types. First, we define the type union for the size and the color. For size, it is small, medium, large.

03:51

For color, it is primary and secondary. And now our desired input style string is simply a combination of any of the size little values followed by a hyen, followed by any of the color little values. And now if we annotate the apply style style parameter to be this particular type type strip correctly catches the typo in the medium primary string. Now, one final thing to point out is that TypeScript has seen that size can be three possible string values. Color can be two possible string values. So the style type can only be the six possible combinations of these two types, which you can see

04:25

by hovering over the style type.

Professional TypeScript Masterclass

Professional TypeScript Masterclass

1.Introduction
free
⏱️ 1:54
2.Setup
free
⏱️ 5:44
3.Primitive Types
free
⏱️ 1:42
4.Instance Types
free
⏱️ 1:52
5.Arrays And Tuples
free
⏱️ 1:38
6.Objects
free
⏱️ 1:33
7.const declarations
free
⏱️ 1:03
8.Function Types
free
⏱️ 1:57
9.Structural Typing
free
⏱️ 2:10
10.Classes in TypeScript
free
⏱️ 1:48
11.Target Compiler Option
free
⏱️ 2:37
12.Generics
⏱️ 3:02
13.Special Types any And unknown
⏱️ 2:00
14.JavaScript to TypeScript
⏱️ 1:32
15.Frontend Projects
⏱️ 3:49
16.Type Assertions
⏱️ 2:15
17.Type Casting
⏱️ 1:16
18.Modules
⏱️ 1:55
19.Type Declarations
⏱️ 4:25
20.Creating NPM packages
⏱️ 3:20
21.Async Await
⏱️ 3:05
22.Running in NodeJS
⏱️ 1:40
23.Lexical this
⏱️ 2:34
24.readonly Modifier
⏱️ 1:59
25.Union Types
⏱️ 2:57
26.Literal Types
⏱️ 2:58
27.Type Narrowing
⏱️ 4:19
28.Discriminated Unions
⏱️ 3:29
29.Class Parameter Properties
⏱️ 1:02
30.Strict Compiler Option
⏱️ 6:18
31.null vs undefined
⏱️ 4:19
32.Intersection Types
⏱️ 2:03
33.Optional Modifier
⏱️ 2:47
34.Non Null Assertion Operator
⏱️ 3:40
35.Interfaces
⏱️ 2:28
36.Interface Declaration Merging
⏱️ 1:01
37.Types vs Interfaces
⏱️ 2:16
38.never Type
⏱️ 3:00
39.implements Keyword
⏱️ 1:25
40.Definite Assignment Assertion
⏱️ 2:31
41.User Defined Type Guards
⏱️ 2:02
42.Assertion Functions
⏱️ 3:42
43.Function Overloading
⏱️ 4:15
44.Call Signatures
⏱️ 2:53
45.Abstract Classes
⏱️ 1:53
46.Index Signatures
⏱️ 3:08
47.Readonly Arrays and Tuples
⏱️ 2:58
48.Double Assertions
⏱️ 2:20
49.const Assertions
⏱️ 3:55
50.this Parameter
⏱️ 2:33
51.Generic Constraints
⏱️ 2:43
52.typeof Type Operator
⏱️ 2:12
53.Lookup Types
⏱️ 3:12
54.keyof Type Operator
⏱️ 3:55
55.Conditional Types
⏱️ 4:39
56.Contitional Types with Unions and never
⏱️ 3:32
57.infer Keyword and `ReturnType<T>`
⏱️ 3:47
58.Mapped Types
⏱️ 2:48
59.Mapped Type Modifiers
⏱️ 3:37
60.Template Literal Type
⏱️ 4:28
61.Partial<T>
⏱️ 1:27
62.Required<T>
⏱️ 1:36
63.Readonly<T>
⏱️ 1:34
64.Record<K, T>
⏱️ 4:05
65.Project References
⏱️ 4:18
66.undefined vs. optional
⏱️ 2:48
67.satisfies Operator
⏱️ 2:42
68.PropertyKey Type
⏱️ 0:57
69.ThisType<T>
⏱️ 4:11
70.Awaited<T>
⏱️ 4:12
71.String Manipulation Types
⏱️ 3:36
72.Mapped Types as Clauses
⏱️ 4:01
73.Union vs Intersection Mental Model
⏱️ 3:36
74.Enums are Bad
⏱️ 8:11