Template literal types let you create new string types by combining other string types. This helps catch mistakes and make your code clearer.
Template literal types in Typescript
type NewType = `${Prefix}${Middle}${Suffix}`;You use backticks (`) around the template, like in JavaScript template strings.
Each part inside ${} must be a string literal type or a union of string literals.
type Greeting = `Hello, ${"World" | "Friend"}!`;type EventName = `${"on" | "off"}${"Click" | "Hover"}`;type CssClass = `btn-${"primary" | "secondary" | "danger"}`;This program defines a type Status with three possible values. Then it creates a template literal type Message that combines a fixed string with Status. The function showMessage only accepts strings matching the Message type. Trying to pass a wrong string causes an error.
type Status = "success" | "error" | "loading"; type Message = `Status is: ${Status}`; function showMessage(msg: Message) { console.log(msg); } showMessage("Status is: success"); // showMessage("Status is: done"); // Error: Argument of type '"Status is: done"' is not assignable to parameter of type 'Message'.
Template literal types only work with string literal types, not general strings.
They help catch errors early by limiting allowed string values.
You can combine them with unions to create many possible string patterns.
Template literal types build new string types by combining smaller string types.
They help TypeScript check if strings match specific patterns.
Use them to make your code safer and clearer when working with strings.