28. What are template literal types, and how do they enhance type safety in TypeScript? Provide an example.

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.

devFlipCards 2025

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.