Advertisement
Intermediate TypeScript, Template Literal Types

How do template literal types combine with mapped type key remapping (the 'as' clause) to auto-generate getter/setter method names?

Short answer

Within a mapped type's key-remapping 'as' clause, you can construct a NEW property name using a template literal type that references the original key (often combined with Capitalize<>), letting you systematically derive a full set of consistently-named methods or properties…

Save TypeScript mock interview
Advertisement
AModel answer
Within a mapped type's key-remapping 'as' clause, you can construct a NEW property name using a template literal type that references the original key (often combined with Capitalize<>), letting you systematically derive a full set of consistently-named methods or properties from an existing type's keys.
type Setters<T> = {
  [K in keyof T as `set${Capitalize<string & K>}`]: (value: T[K]) => void
};
interface Person { name: string; age: number; }
type PersonSetters = Setters<Person>;
// { setName: (value: string) => void; setAge: (value: number) => void }
Real-world example
Auto-generating a complete, consistently-named setter interface from a plain data model interface without manual duplication.
Likely follow-ups
  • Why does the key need to be written as `string & K` rather than just `K` inside the template literal here?
Related topics