Template Literals and Mapped Types
Master the power of dynamic type generation with template literals and mapped types in TypeScript.
We'll cover the following...
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.
Explanation:
Line 1: This declares a union type
Statusrepresenting allowed status values.Line 2: This uses a template literal type to construct
PrefixedStatusby prefixing eachStatusvariant with"api_". The resulting type is"api_pending" | "api_success" | "api_error".Line 4: This declares a variable
exampleStatuswith 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 ...