0
0
Typescriptprogramming~5 mins

Template literal type syntax in Typescript

Choose your learning style9 modes available
Introduction

Template literal types let you create new text types by combining other text types. This helps you make flexible and clear type rules.

When you want to build new string types by joining other string types.
When you need to check if a string matches a certain pattern in types.
When you want to create types for formatted strings like URLs or commands.
When you want to reuse parts of string types to avoid repeating code.
Syntax
Typescript
type NewType = `${Type1}${Type2}`;

Use backticks ` around the template.

Inside ${}, put other string or literal types.

Examples
This creates a type for strings starting with 'Hello, ' and ending with '!'.
Typescript
type Greeting = `Hello, ${string}!`;
This type can be 'onClick', 'onHover', or 'onFocus'.
Typescript
type EventName = `on${'Click' | 'Hover' | 'Focus'}`;
This type matches sizes like '10px' or '2em'.
Typescript
type CssSize = `${number}px` | `${number}em`;
Sample Program

This program defines a type Message that must start with 'Status: ' followed by either 'success' or 'error'. It shows how to use this type with variables.

Typescript
type Status = 'success' | 'error';
type Message = `Status: ${Status}`;

const good: Message = 'Status: success';
const bad: Message = 'Status: error';

// This will cause an error if uncommented:
// const wrong: Message = 'Status: warning';

console.log(good);
console.log(bad);
OutputSuccess
Important Notes

Template literal types only work with string, number, or boolean literal types inside ${}.

They help catch mistakes early by checking string patterns in types.

Summary

Template literal types build new string types by combining others.

They use backticks and ${} to insert types.

Useful for creating clear and flexible string patterns in types.