Rename keys with as in a mapped type
Add an as clause to a mapped type to rename every key, such as turning name into getName with a template literal type. Added in TypeScript 4.1.
Given a User type, you want a type for an object of getters: getName returning the name, getAge returning the age. A key remapping clause rewrites each key as it is mapped.
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
interface User {
name: string;
age: number;
}
const getters: Getters<User> = {
getName: () => 'Ada',
getAge: () => 36,
};
console.log(getters.getName(), getters.getAge());Ada 36The as clause after keyof T computes the new name for each key, and the right-hand side keeps the original T[K] as the return type. Capitalize is one of the built-in string manipulation types, and string & K narrows the key to a string, because a key may also be a number or a symbol. Key remapping was added in TypeScript 4.1.
Mapping a key to never removes it, so as K extends 'id' ? never : K filters keys. Remapping makes the mapped type non-homomorphic in some cases, so check that optional and readonly modifiers still carry over where you need them.