Template literal types let you create new string types by combining other string types. This helps catch mistakes early and makes your code smarter.
Why template literal types are powerful in Typescript
type NewType = `${stringPart1}${stringPart2}`;You use backticks (`) to create template literal types, similar to JavaScript template strings.
Inside the backticks, you can insert other types using ${}.
type Greeting = `Hello, ${string}!`;type EventName = `${'click' | 'hover'}Event`;type CssClass = `btn-${'primary' | 'secondary'}`;This program defines a type Message that must start with 'Status: ' followed by one of the allowed statuses. The function showMessage only accepts those strings. If you try to pass a wrong string, TypeScript will show an error before running.
type Status = 'success' | 'error' | 'loading'; type Message = `Status: ${Status}`; function showMessage(msg: Message) { console.log(msg); } showMessage('Status: success'); // showMessage('Status: done'); // Error: Argument of type '"Status: done"' is not assignable to parameter of type 'Message'.
Template literal types help catch errors before running your code.
You can combine them with unions to create many string options easily.
They work only at compile time and do not affect the JavaScript output.
Template literal types build new string types by combining others.
They help TypeScript check string formats and catch mistakes early.
They make your code safer and easier to understand.