Skip to content
jshacks.dev
TypeScript

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.

1 min read
Summarize in AI

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.

getters.tsTypeScript
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());
Text
Ada 36

The 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.

Share

More snippets

TypeScript

Make every property required with Required

Required of T removes the question mark from every property, which types a config object after its defaults have been filled in. TypeScript 5 and earlier.

1 min read
TypeScript

Declare types for an untyped module

Write a small .d.ts file with declare module so an untyped package gets real function signatures, instead of an implicit any error. TypeScript 5.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.