Template literal types in TypeScript allow you to create types based on strings that are combined with other types. This enables more precise modeling of data that has a strictly defined structure. These types use string template literals, which allow you to create new types based on existing string values.
Example:
type Greeting = `Hello, ${string}!`; const greeting1: Greeting = 'Hello, World!'; // OK const greeting2: Greeting = 'Hi, World!'; // Error, 'Hi' doesn't match the pattern
In this example, the Greeting
type only accepts strings that start with 'Hello,' and end with an exclamation mark. This ensures that only appropriate values can be assigned to variables of this type, increasing type safety.