Course contentsShow
← TypeScript
Lesson 755 of 1,79617. Mapped TypesFree lesson

Using Template Literals in as Clauses

Combine template literal types with as to create dynamic key transformations based on original keys.

Using Template Literals in as Clauses

What you'll learn: How to dynamically rename mapped type keys using template literal types inside as clauses.

The Core Idea

When you combine the as clause with template literal types, you unlock powerful key transformation patterns. Instead of just filtering or copying keys, you can transform them programmatically — adding prefixes, suffixes, changing case, or even constructing entirely new key names based on the original keys.

Think of it like a find-and-replace operation that works at the type level: you're taking the original property names and running them through a transformation formula.

How It Works

The as clause lets you specify what each key should become. When you use a template literal inside that clause, you can embed the original key (represented by K) into a string pattern:

type Prefixed<T> = {
  [K in keyof T as `get${K & string}`]: T[K]
}

type User = {
  name: string
  age: number
}

type PrefixedUser = Prefixed<User>
// Result: { getName: string; getAge: number }

Notice K & string — this ensures TypeScript treats the key as a string for template literal operations.

Real-World Example: Event Names

type EventMap<T> = {
  [K in keyof T as `on${Capitalize<K & string>}`]: (value: T[K]) => void
}

type Data = {
  click: boolean
  hover: boolean
}

type Events = EventMap<Data>
// Result: { onClick: (value: boolean) => void; onHover: (value: boolean) => void }

You've created type-safe event handler names directly from your data shape!

Key Takeaway: Template literals in as clauses let you programmatically rename keys during mapping, enabling patterns like prefixing (get/set), suffixing, or case transformations, all while preserving type safety.