# Key Remapping (as)

> Renaming keys dynamically during a mapped type loop.

Subject: TypeScript | Lesson 31 of 54 | 5 min read
Interactive lesson: https://codewithanimation.in/typescript/key-remapping
Previous: [Mapped Types](https://codewithanimation.in/typescript/mapped-types.md) | Next: [Template Literal Types](https://codewithanimation.in/typescript/template-literal-types.md)

## Changing Keys on the Fly

In TypeScript 4.1+, you can change the actual name of a key while you are looping over it in a mapped type.

By using the `as` keyword inside the bracket notation, you can transform the key, format it, or even filter it out completely.

## Getters, Setters, and Filtering

If you have a `User` type with `{ name: string; age: number }`, and you want to generate a store object with `{ getName: () => string; getAge: () => number }`, key remapping makes it trivial.

It allows you to derive highly complex, correctly typed APIs directly from simple base types.

## Syntax

```typescript
type User = { name: string; age: number };

// Add 'get' prefix, capitalize the original key, and return a function.
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

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

## Common mistake: Filtering out Keys with never

You can completely remove keys from a mapped type by remapping them to `never`.

For example, `[K in keyof T as K extends "password" ? never : K]` will loop over the keys, and if it sees "password", it remaps it to `never`, causing TypeScript to drop it entirely from the final object.

## Tip: The string & K Trick

You often see `string & K` used in template literal types like `Capitalize<string & K>`. This is because `keyof T` can include `symbol` or `number` keys, and the `Capitalize` utility only accepts strings. The `& string` intersection forces it to be a string.

## Try it: Try it

Watch the `as` keyword physically rename keys dynamically during a mapped type loop, converting plain properties into prefixed getter functions.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/key-remapping

## Check yourself

### Question 1

How do you completely drop a key from a mapped type using key remapping?

- A. Remap it to 'void'.
- B. Remap it to 'undefined'.
- C. Remap it to 'never'.

Correct answer: C

Remapping to 'never' is the standard way to filter out keys during a mapped type loop.

- Why not A: Void means a function returns nothing, but the key would still exist.
- Why not B: The key would still exist, but its value type would be undefined.

## Remember this

- Key remapping uses the syntax `[K in keyof T as NewKeyType]`.
- It is incredibly powerful when combined with Template Literal Types.
- Remapping a key to `never` removes it from the final type.
- It avoids the need for creating multiple boilerplate interfaces for getters/setters.
