What are template literal types in Typescript ?
Last Updated :
24 Jan, 2025
Improve
Template literal types in TypeScript allow the construction of new string literal types by combining existing string literal types using template literal syntax.
- They enable the creation of complex string patterns by embedding unions and other literal types within template literals.
- This feature enhances type safety by allowing developers to define and enforce specific string formats at the type level.
type Size = "small" | "medium" | "large";
type SizeMessage = `The selected size is ${Size}.`;
let message: SizeMessage;
message = "The selected size is small."; // Valid
message = "The selected size is extra-large."; // Error
- Size is a union type representing possible sizes.
- SizeMessage is a template literal type that constructs specific string patterns incorporating each Size value.
- The variable message can only be assigned strings that match the SizeMessage pattern.
Output:
Type '"The selected size is extra-large."' is not assignable to type 'SizeMessage'.
More Example of template literal types in Typescript
Defining Paths Using TypeScript Literals
type ApiEndpoints = "users" | "posts" | "comments";
type ApiPath = `/api/${ApiEndpoints}`;
const userPath: ApiPath = "/api/users";
const invalidPath: ApiPath = "/api/unknown";
- ApiEndpoints is a union type representing possible API endpoint names.
- ApiPath is a template literal type that dynamically constructs string patterns prefixed with /api/ followed by one of the ApiEndpoints.
- userPath is valid because it matches the constructed pattern, while invalidPath throws an error.
Output:
Type '"/api/unknown"' is not assignable to type 'ApiPath'.
Formatting Messages Using Template Literals
type Status = "success" | "error" | "loading";
type StatusMessage = `The operation is ${Status}.`;
const successMessage: StatusMessage = "The operation is success.";
const invalidMessage: StatusMessage = "The operation is pending.";
- Status is a union type representing possible operation statuses.
- StatusMessage constructs string patterns to describe the status of an operation.
- successMessage is valid because it matches the pattern, but invalidMessage throws an error as "pending" is not part of Status.
Output:
Type '"The operation is pending."' is not assignable to type 'StatusMessage'.