Template Literals and Mapped Types
Master the power of dynamic type generation with template literals and mapped types in TypeScript.
The deeper we go into TypeScript, the more powerful the type system becomes. Types may be static, but they’re far from rigid. They can be composed, transformed, and even generated based on other types—all at compile time. This lesson introduces two of the most powerful tools in TypeScript: template literal types and mapped types. These tools help create types that respond to patterns, encode business rules, and scale effortlessly across large codebases. By the end of this lesson, we won’t just write types—we’ll generate them. Let’s take a practical approach.
Template literal types
Sometimes our types need to describe structured variations, not just fixed values. Template literal types allow us to construct new string types by combining other types inside a pattern, like building "getName"
from "name"
, or "app_theme"
from "theme"
. Instead of manually listing out every possibility, we encode the logic of how those strings are formed once and let TypeScript generate the rest.
type Status = "pending" | "success" | "error";type PrefixedStatus = `api_${Status}`; // "api_pending" | "api_success" | "api_error"const exampleStatus: PrefixedStatus = "api_success";console.log(exampleStatus);const wrongStatus: PrefixedStatus = "api_done"; // Error: Type '"api_done"' is not assignable to type 'PrefixedStatus'
Explanation:
Line 1: This declares a union type
Status
representing allowed status values.Line 2: This uses a template literal type to construct
PrefixedStatus
by prefixing eachStatus
variant with"api_"
. The resulting type is"api_pending" | "api_success" | "api_error"
.Line 4: This declares a variable
exampleStatus
with typePrefixedStatus
, and assigns a valid value"api_success"
.Line 8: This demonstrates a type error by attempting to assign
"api_done"
—which is not part of the generated type toPrefixedStatus
. TypeScript correctly rejects this at compile time.
Template literals let us ...