×

typescript · level 3 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Rename keys inside a mapped type with as.

Inside a mapped type, as gives each new property a different name. This is . Below, as with the pattern get${Capitalize<K & string>} turns the key name into getName, so a whole set of method names grows from one type.

One snag: keys can be numbers as well as strings, and Capitalize only takes strings. K & string keeps only the string part. The & makes an : a value must fit both sides at once. Remap a key to never and it disappears.

type Getters<T> = {
  [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K];
};
interface Pet {
  name: string;
  age: number;
}
const rex: Getters<Pet> = {
  getName: () => "Rex",
  getAge: () => 4,
};
console.log(rex.getName(), rex.getAge() + 1);

() => T[K] is a function type for a function that takes nothing and hands back that property's type.