Course contentsShow
← TypeScript
Lesson 846 of 1,79619. Template Literal TypesFree lesson

Key Remapping with as and Template Literals

Combine the 'as' clause in mapped types with template literals to rename keys during mapping.

Key Remapping with as and Template Literals

You'll learn how to transform object keys during mapping by combining the as clause with template literal types to create powerful type transformations.


The Core Idea

You already know that the as clause lets you rename keys in mapped types, and you've seen template literals create dynamic string types. When you combine these two features, you unlock the ability to systematically transform every key in an object type according to a pattern.

Think of it like a factory assembly line: instead of hand-stamping each product one by one, you set up a template that automatically processes every item that comes down the line. The as clause is your stamping machine, and template literals define the pattern.

How It Works

Here's the syntax pattern:

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

The as clause intercepts each original key K and replaces it with a new key built from a template literal. The K & string part ensures TypeScript treats the key as a string (since keyof can include symbols and numbers).

Practical Example

type User = {
  name: string;
  age: number;
  email: string;
}

type PrefixedUser = {
  [K in keyof User as `user_${K & string}`]: User[K]
}

// Result:
// {
//   user_name: string;
//   user_age: number;
//   user_email: string;
// }

You can also use intrinsic string types:

type GetterMethods<T> = {
  [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K]
}

type UserGetters = GetterMethods<User>
// {
//   getName: () => string;
//   getAge: () => number;
//   getEmail: () => string;
// }

Key Takeaway: Combining as with template literals in mapped types lets you programmatically rename every key according to a pattern, enabling powerful type transformations like adding prefixes, creating getter methods, or adapting naming conventions—all with type safety intact.