May 14, 2025
Template literals in TypeScript
You might know template strings in JavaScript. TypeScript offers with template literals something similiar just on type level. It’s useful to keep naming conventions or generally to precise the structure of a string. Look at the following short examples.
type Color = `#${string}`;
const colorA: Color = '#ffffff'; // ✅
const colorB: Color = '000000'; // ❌ Type error
type EventName = `on${Capitalize<string>}`;
const eventNameA: EventName = 'onClick'; // ✅
const eventNameB: EventName = 'onclick'; // ❌ Type error
type Subdomain = 'dk' | 'no' | 'se';
type Href = `https://${Subdomain}.xyz.com`;
const hrefA: Href = 'https://dk.xyz.com'; // ✅
const hrefB: Href = 'https://is.xyz.com'; // ❌ Type error