How would you write a mapped type using an index signature-like syntax that also applies key remapping via 'as'?
Short answer
Combine a mapped type's `[K in Keys]` syntax with the 'as' clause to transform each resulting key name (e.g.
Advertisement
AModel answer
Combine a mapped type's `[K in Keys]` syntax with the 'as' clause to transform each resulting key name (e.g. prefixing it), producing a new object type whose keys are systematically derived from — but different from — the original key set, unlike a plain index signature which can't rename keys.
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
interface Person { name: string; age: number; }
type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number }Real-world example
Auto-generating a getter-method interface from a plain data interface, avoiding manual duplication.
Likely follow-ups
- Could a plain index signature achieve this same key-renaming effect on its own?
Related topics