TypeScript · Middle · Question 28 of 75

How do you rename keys in a mapped type?

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

Explanation

Key remapping (TS 4.1+): Getters<{ name: string }> → { getName: () => string }. If the expression after as produces never, the key is dropped - that's how properties are filtered by value type. string & K is needed because keys can be symbols or numbers.

Further reading

Problem with a question

TypeScript · Middle · question 28

Test yourself

Take the TypeScript · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz