JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstypescript
PrevNext
typescript
senior
template-literal-types

What are template literal types and how do you use them?

template-literal-types
string-manipulation
type-safety
advanced
Quick Answer

Template literal types use the same syntax as template strings but operate on types. They can create union types from string combinations, validate string patterns, and transform string types. Useful for type-safe event names, CSS properties, and API routes.

Detailed Explanation

Template Literal Syntax:

  • Same as JS template strings: \${Type}``
  • Can interpolate string literal types
  • Distributes over unions
  • Creates new string literal types

Intrinsic String Types:

  • Uppercase<T>: Convert to uppercase
  • Lowercase<T>: Convert to lowercase
  • Capitalize<T>: Capitalize first letter
  • Uncapitalize<T>: Lowercase first letter

Use Cases:

  • Event handler names
  • CSS-in-JS property names
  • API route typing
  • Configuration keys

Code Examples

Basic template literal types
// Simple string combination
type Greeting = `Hello, ${string}!`;

const g1: Greeting = 'Hello, World!';  // OK
const g2: Greeting = 'Hi, World!';     // Error

// Union distribution
type Color = 'red' | 'blue' | 'green';
type Size = 'small' | 'large';

type ColorSize = `${Color}-${Size}`;
// 'red-small' | 'red-large' | 'blue-small' | 'blue-large' | 'green-small' | 'green-large'

// Event names pattern
type EventName = `on${Capitalize<'click' | 'hover' | 'focus'>}`;
// 'onClick' | 'onHover' | 'onFocus'

// Intrinsic string manipulation
type Upper = Uppercase<'hello'>; // 'HELLO'
type Lower = Lowercase<'HELLO'>; // 'hello'
type Cap = Capitalize<'hello'>;  // 'Hello'
type Uncap = Uncapitalize<'Hello'>; // 'hello'

Resources

TypeScript - Template Literal Types

docs

Related Questions

How do mapped types work in TypeScript?

senior
mapped-types

How do conditional types work in TypeScript?

senior
conditional-types
Previous
How do mapped types work in TypeScript?
Next
How do you handle complex generic constraints and variance in TypeScript?