MediumJavaScriptTypeScript

Mapped Types — Key Remapping

TypeScriptTypesObjects/Maps

TypeScript's key remapping (the as clause in mapped types) lets you transform every key while preserving the value types:

// Prefix all keys with a string:
type Prefixed<T, P extends string> = {
  [K in keyof T as `${P}${Capitalize<string & K>}`]: T[K]
};

// Convert each property into a getter method:
type Getterized<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};

// Invert keys ↔ values:
type Inverted<T extends Record<string, string>> = {
  [V in T[keyof T]]: keyof T
};

Your Task

Implement three runtime utilities:

FunctionExample
prefixKeys(obj, 'data_'){ name: 'Alice' }{ data_name: 'Alice' }
invertObject(obj){ a: 'x', b: 'y' }{ x: 'a', y: 'b' }
toGetterObject(obj){ count: 5 }{ getCount: () => 5 }

Sample tests

Test #1prefix all keys
Input: ["prefixKeys",{"age":30,"name":"Alice"},"data_"]
Output: {"data_age":30,"data_name":"Alice"}
Test #2swap keys and values
Input: ["invertObject",{"a":"x","b":"y"}]
Output: {"x":"a","y":"b"}
Test #3getter keys with values
Input: ["toGetterObject",{"count":5,"label":"hi"}]
Output: {"getCount":5,"getLabel":"hi"}