Contents (10)
[Typescript] Template Literal Types
I'm planning to cover TypeScript features one at a time, and the first feature to get picked is Template Literal Types. Literal types themselves aren't hard, but to understand 2. Usage Examples, you'll probably need to know about generic types and type inference (infer).
1. Literal Types and Template Literal Types
A Template Literal type is a type that lets you build and combine string literals using template string syntax (backticks ``).
Template Literal types and String Literal types can be used in all sorts of situations, such as generating design tokens that follow string rules or automatically generating types from an Object's keys. Below is an explanation of each type.
Literal Type: A type that uses a specific string or number as the type itself, rather than just a general type like string or number.
type Direction = "left" | "right";const direction:Direction = "left"; ✅const direction:Direction = "up"; ❌ // Can only have the values left and right.Type '"up"' is not assignable to type '"left" | "right"'const direction:string = "up"; ✅ // The string type accepts any string.Template Literal: A type built by combining String Literals using template string syntax (backticks ``).
type Fruit = "apple" | "banana" | "mango";type Sentence = `I like ${Fruit}`;const sentence:Sentence = "I like apple"; ✅const sentence:Sentence = "I hate apple"; ❌ // It's not I like.Type '"I hate apple"' is not assignable to type '"I like apple" | "I like banana" | "I like mango"'.const sentence:Sentence = "I like melon"; ❌ // This fruit isn't in the Fruit type.Type '"I like melon"' is not assignable to type '"I like apple" | "I like banana" | "I like mango"'.2. Template Literal Usage Examples
Let me show you a few examples of situations where Template Literal can be used. I've brought one example where I used Template Literal myself, and one usage example from the official docs.
2.1 Design Tokens - Typography
I used this feature in a design system to define Typography design tokens that follow the {type}-{Size}-{Weight} rule. Here's the example code.
type FontType = "title" | "body";type FontSize = "sm" | "md" | "lg";type FontWeight = "regular" | "medium" | "bold";type FontVariant = `${FontType}-${FontSize}-${FontWeight}`; // 2 FontTypes 3 FontSizes * 3 FontWeights = 18 combinations;// "title-sm-regular", "title-md-regular", "title-md-bold", "title-md-regular... and so on, creating a union type of 18 strings.type FontProperties = Pick< CSSProperties, "fontWeight" | "lineHeight" | "fontSize" | "letterSpacing">;type Typography = Record<FontVariant, FontProperties>;const typography: Typography = { "body-lg-bold": { fontSize: "1rem", fontWeight: 700, letterSpacing: 0, lineHeight: 1, }, "body-lg-medium": { fontSize: "1rem", fontWeight: 500, letterSpacing: 0, lineHeight: 1, }, //...};If you want to apply the Typography type even more tightly, you can build on it. The next example automatically locks the CSS fontWeight type according to the FontWeight.
import {CSSProperties} from "react";type FontType = "title" | "body";type FontSize = "sm" | "md" | "lg";type FontWeightValueMap = { regular: 400; medium: 500; bold: 700;};// If you also want to use it as a variable, make it a variable with const fontWeightValueMap. Get the type with the typeof operator.type FontWeight = keyof FontWeightValueMap; // "regular" | "medium" | "bold"type FontWeightCSSProperty<FW extends FontWeight> = { fontWeight: FontWeightValueMap[FW];}; //Locks the value to a CSS literal type number according to FontWeight.type FontVariant = `${FontType}-${FontSize}-${FontWeight}`; // 18 tokenstype ExtractFontWeight<FV extends FontVariant> = FV extends `${string}-${string}-${infer FW}` ? FW : never; // Extract FontWeight from FontVarianttype FontProperties<FV extends FontVariant> = Pick< CSSProperties, "lineHeight" | "fontSize" | "letterSpacing"> & FontWeightCSSProperty<ExtractFontWeight<FV>>; //fontWeight's value is determined by the Font Weight of the Font Variant.type Typography = { [key in FontVariant]: FontProperties<key>;};const typography: Typography = { "body-lg-bold": { fontSize: "1rem", fontWeight: 700, ✅ letterSpacing: 0, lineHeight: 1, }, "body-lg-medium": { fontSize: "1rem", fontWeight: 700, ❌ Type error, because medium must have the value 500.Type '700' is not assignable to type '500' letterSpacing: 0, lineHeight: 1, }, //...};If you ask me which of the two type setups is better for a design system, it depends on what benefits you want, or on the situation. If you don't plan to touch the design token structure anymore, or it's a project you need to wrap up quickly, worrying about types is nothing but a waste of time. But if it's an important design system that's even hooked up to Figma, and you're thinking about version management and automatic syncing to Figma, it seems better to set up the types according to a clear design plan. In conclusion, I think it's best to decide based on the situation: available people, skill level, spare time, and so on.
2.2 Official Docs Example
Below is an example from the official docs where a function's type is created automatically based on an object's literal key values and the types of their values. Even if the object's value types vary, developers can comfortably write code with the matched types.
type PropEventSource<T> = { on<Key extends string & keyof T> (eventName: `${Key}Changed`, callback: (newValue: T[Key]) => void): void;};// ${key value of T} + "Changed" becomes the eventName. callback's newValue becomes ${the type of the value matched to T's key value}/// Create a "watched object" with an `on` method/// so that you can watch for changes to properties.declare function makeWatchedObject<T>(obj: T): Type & PropEventSource<T>;const person = makeWatchedObject({ firstName: "Saoirse", lastName: "Ronan", age: 26});person.on("firstNameChanged", (newName) => {console.log(newName)});// The 1st parameter of the on function becomes `{key}Changed`, and newName in the 2nd parameter function automatically becomes the string type. person.on("ageChanged", newAge => {console.log(newAge)})// Likewise, it's ${person's key value = "age"}+"Changed", and newAge takes person["age"]'s type.3. Related Utility Types
Below are utility types related to Template Literal and String Literal. I took them from the official docs.
3.1 Uppercase
A utility that converts a type so that every character is uppercase.
type Greeting = "Hello, world"type ShoutyGreeting = Uppercase<Greeting> // "HELLO, WORLD" typetype ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`type MainID = ASCIICacheKey<"my_app"> // "ID-MY_APP" type3.2 Lowercase
A utility that converts a type so that every character is lowercase.
type Greeting = "Hello, world"type QuietGreeting = Lowercase<Greeting> // "hello, world" typetype ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`type MainID = ASCIICacheKey<"MY_APP"> // "id-my_app" type3.3 Capitalize
A utility that converts a type so that the first character is uppercase.
type Greeting = "hello, world"type ShoutyGreeting = Uppercase<Greeting> // "Hello, world" type3.4 Uncapitalize
A utility that converts a type so that the first character is lowercase
type Greeting = "HELLO WORLD"type ShoutyGreeting = Uppercase<Greeting> // "hELLO WORLD" type