Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons

© 2026 BraveProgrammer. All rights reserved.

  1. Courses
  2. /
  3. TypeScript Mastery

Lesson 46 of 56 · Typescript

Template Literal Types

Duration: 20 minutes

Creating string patterns

type Event = `on${Capitalize<string>}`;
type ClickEvent = Event; // "onClick", "onHover", etc.

Union of literals via interpolation

type Size = "small" | "medium" | "large";
type SizeClass = `size-${Size}`; // "size-small" | "size-medium" | "size-large"

Using infer with template literals

type ExtractPrefix<S extends string> = S extends `${infer P}_SUFFIX` ? P : never;
type X = ExtractPrefix<'hello_SUFFIX'>; // "hello"

Practical use – CSS‑in‑JS

const btnClass: SizeClass = 'size-medium';

Info

Template literal types provide compile‑time string validation – ideal for CSS class names, API routes, and event names.

Previous: Advanced Generics – Variadic Tuple TypesNext: Symbol & Iterator Protocols