Sub topic 8
Renaming Object Keys with as Clauses
This chapter shows how to rename or drop the keys of an object type by combining a mapped type, an as clause, and a template literal type. It assumes you know basic type aliases, generics with constraints, union types, and mapped types such as { [K in keyof T]: T[K] }. It also assumes you have read the earlier chapters on template literal syntax, Capitalize and the other case helpers, and infer in templates.
The problem: mapped types keep the original keys
A plain mapped type changes the value of each property but keeps its name:
type Person = { name: string; age: number };
type Lazy<T> = { [K in keyof T]: () => T[K] };
type LazyPerson = Lazy<Person>;
// { name: () => string; age: () => number }Often you want new names too, such as getName instead of name. Before TypeScript 4.1 you had to build a second type by hand. The as clause fixes this. It lets you compute a new key from each original key.
Anatomy of an as clause
type Mapped<T> = {
[K in keyof T as NewKey<K>]: NewValue<T[K]>;
};The compiler evaluates the mapped type like this:
- It iterates over each member
Kof the constraint afterin. - It evaluates the type after
as, withKin scope. The result becomes the property name in the output type. - It evaluates the value type after the colon, where
Kis still the original key. That is whyT[K]keeps working.
The as type must be assignable to string | number | symbol. This is the same restriction that applies to any property key.
The classic example: getters
This example comes from the topic plan and combines three earlier ideas:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type Person = { name: string; age: number };
type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number }Here is what each part does:
keyof T & stringkeeps only the string keys.keyof Thas typestring | number | symbol, andCapitalizeaccepts only strings. Without& stringthe compiler reports that the key type is not assignable tostring.- `
get${Capitalize<K>}is the template literal type. ForK = "name"it produces"getName"`. T[K]still refers to the original key, so each value type is preserved.
The same type can describe a real function. This function builds the getters at runtime:
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
function withGetters<T extends object>(obj: T): Getters<T> {
const result: Record<string, () => unknown> = {};
for (const [key, value] of Object.entries(obj)) {
const name = `get${key.charAt(0).toUpperCase()}${key.slice(1)}`;
result[name] = () => value;
}
return result as unknown as Getters<T>;
}
const person = withGetters({ name: "Ada", age: 36 });
const n: string = person.getName(); // "Ada"
const a: number = person.getAge(); // 36
// person.name; // Error: Property 'name' does not existThe type and the runtime code are separate. The compiler does not check that result really contains these names, which is why the function needs the as unknown as cast. You are responsible for keeping the two in sync.
Setters, prefixes, and suffixes
Any template literal works in the as clause. A setter type follows the same pattern, with the key in the parameter:
type Setters<T> = {
[K in keyof T & string as `set${Capitalize<K>}`]: (value: T[K]) => void;
};
type Accessors<T> = Getters<T> & Setters<T>;
type PersonAccessors = Accessors<{ name: string; age: number }>;
// getName, getAge, setName, setAgePrefixes and suffixes work the same way. ` ${K}Changed turns name into nameChanged. For snake_case or kebab-case you would combine this with the infer` techniques from the previous chapter.
Filtering keys with never
If the as clause evaluates to never for a key, that key is left out of the result. A conditional type in the as position therefore acts as a filter:
type OnlyFunctions<T> = {
[K in keyof T as T[K] extends (...args: any[]) => any ? K : never]: T[K];
};
type Service = {
url: string;
retries: number;
connect: () => void;
send: (data: string) => boolean;
};
type ServiceMethods = OnlyFunctions<Service>;
// { connect: () => void; send: (data: string) => boolean }Here the key is kept unchanged (K) or dropped (never). You can also drop a specific key with Exclude:
type Without<T, Keys extends PropertyKey> = {
[K in keyof T as Exclude<K, Keys>]: T[K];
};
type NoAge = Without<{ name: string; age: number }, "age">;
// { name: string }For this case you can also use the built-in Omit. The as form becomes useful when the condition looks at the value or at the key's shape, which Omit cannot do.
Removing a prefix with infer
The as clause is a type position, so it can hold a conditional type with infer. This type strips a known prefix from every key that has it:
type RemovePrefix<T, P extends string> = {
[K in keyof T as K extends `${P}${infer Rest}` ? Rest : K]: T[K];
};
type Raw = { data_id: number; data_name: string; other: boolean };
type Clean = RemovePrefix<Raw, "data_">;
// { id: number; name: string; other: boolean }For K = "data_id", the pattern matches and Rest is "id". For K = "other", the pattern does not match, so the key stays as it is. Symbol keys also take the second branch, because a symbol never matches a string pattern. This is why the type needs no & string.
One key becoming many keys
The as clause can produce a union. Each member of the union becomes a separate property, and each gets the same value type:
type Events<T> = {
[K in keyof T & string as `${K}Changed` | `${K}Reset`]: (value: T[K]) => void;
};
type PersonEvents = Events<{ name: string; age: number }>;
// {
// nameChanged: (value: string) => void;
// nameReset: (value: string) => void;
// ageChanged: (value: number) => void;
// ageReset: (value: number) => void;
// }This relies on the union expansion from earlier in the tutorial. The template distributes over the union in K, and the | adds a second alternative for each key.
Iterating over a union of objects
The in part does not have to be keyof. It can be any union whose members are assignable to a key type, including a union of object types. You then pick the key from a property of each member, which suits discriminated unions:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; side: number };
type ShapeHandlers = {
[S in Shape as `on${Capitalize<S["kind"]>}`]: (shape: S) => void;
};
// {
// onCircle: (shape: { kind: "circle"; radius: number }) => void;
// onSquare: (shape: { kind: "square"; side: number }) => void;
// }In this form S is a whole object type, not a key. Each handler receives exactly the member of the union it belongs to, with no manual narrowing.
Gotchas
Keys that are not strings
keyof T can include numbers and symbols. You have two ways to deal with them:
| Approach | Syntax | Effect on non-string keys |
|---|---|---|
| Intersect the iteration | `[K in keyof T & string as ...]` | They are skipped before the `as` clause runs. |
| Test inside the `as` clause | `[K in keyof T as K extends string ? \`get${Capitalize<K>}\` : never]` | They map to `never`, so they are dropped. |
Both forms drop non-string keys. The second keeps the plain keyof T form. That form is the one the compiler recognizes as copying modifiers such as readonly and ? from the source type. If you need those modifiers to carry over, prefer the second form. If you use the first form, check the result in your editor instead of assuming.
Two keys mapping to the same name
If two original keys produce the same new key, TypeScript does not report an error. The property gets the union of the value types:
type Collapse = { [K in "a" | "b" as "x"]: K };
// { x: "a" | "b" }This can hide a mistake. For example, a type with both name and Name would collide under a naive Capitalize rename. If a collision matters to you, write a test type that compares keyof of the result with the keys you expect.
Optional properties and undefined
If a source property is optional, T[K] includes undefined. A getter built from it has the type () => string | undefined. That is usually correct, but it means the getter type is not always the plain value type.
Error messages
Errors in mapped types with as clauses often point at the whole type alias. When one fails, test the key expression alone with a small alias. For example, check that ` get${Capitalize<"name">} gives "getName"`. Then add the mapped type around it.
Summary of patterns
| Goal | `as` clause | Column |
|---|---|---|
| Add a prefix | `` `get${Capitalize<K>}` `` | |
| Add a suffix | `` `${K}Changed` `` | |
| Remove a prefix | `K extends `${P}${infer Rest}` ? Rest : K` | |
| Filter by value | `T[K] extends X ? K : never` | |
| Drop named keys | `Exclude<K, "a" \ | "b">` |
| Make several keys from one | `` `${K}A` \ | `${K}B` `` |
Exercise
Write a type Flags<T> that takes an object type and produces a new object type where every string key K becomes ` is${Capitalize<K>} and every value becomes boolean. What does Flags<{ active: string; admin: number }>` produce?
Show answer
type Flags<T> = { [K in keyof T & string as is${Capitalize<K>}]: boolean }; The result is { isActive: boolean; isAdmin: boolean }. The value type ignores T[K] because every flag is a boolean.
Exercise
A type Api has the keys user_id, user_name, and token. You want a type that keeps only the keys starting with user_ and removes that prefix, so the result has id and name only. Which part of the as clause drops token, and why does it work?
Show answer
The false branch of the conditional returns never. Write [K in keyof Api as K extends user_${infer Rest} ? Rest : never]: Api[K]. For user_id the pattern matches and the key becomes "id". For token the pattern fails, the as clause evaluates to never, and a key mapped to never is removed from the result.