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.
- 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
- 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
- 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'.