Implement the type of `just-flip-object`. Examples: Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.
In this medium-level challenge, you'll implement a Flip type that swaps the keys and values of an object type, so that each value becomes a key and each key becomes a value.
Implement the type of just-flip-object. Examples:
Flip<{ a: "x", b: "y", c: "z" }>; // {x: 'a', y: 'b', z: 'c'}
Flip<{ a: 1, b: 2, c: 3 }>; // {1: 'a', 2: 'b', 3: 'c'}
Flip<{ a: false, b: true }>; // {false: 'a', true: 'b'}No need to support nested objects and values which cannot be object keys such as arrays
Change the following code to make the test cases pass (no type check errors).
The main challenge is that object values like boolean or number cannot directly be used as keys. We need to convert them to their string representation using template literal types.
type Flip<T extends Record<string, string | number | boolean>> = {
[K in keyof T as `${T[K]}`]: K
}How it works:
[K in keyof T as \$`]iterates over each keyKinTand remaps it using theas` clause\$`converts the value at keyKto its string literal representation, which allowsnumber, boolean, and string` values to all become valid property keysK assigns the original key as the new value{ pi: 3.14, bool: true } becomes { '3.14': 'pi', 'true': 'bool' }This challenge helps you understand key remapping with the as clause in mapped types and how to apply this concept in real-world scenarios.
This challenge is originally from here.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount