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).
type cases = [
Expect<Equal<{ a: 'pi' }, Flip<{ pi: 'a' }>>>,
Expect<NotEqual<{ b: 'pi' }, Flip<{ pi: 'a' }>>>,
Expect<Equal<{ 3.14: 'pi'; true: 'bool' }, Flip<{ pi: 3.14; bool: true }>>>,
Expect<
Equal<{ val2: 'prop2'; val: 'prop' }, Flip<{ prop: 'val'; prop2: 'val2' }>>
>,
]
Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.
One-time payment. Lifetime access.
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 `${T[K]}`] iterates over each key K in T and remaps it using the as clause`${T[K]}` converts the value at key K to its string literal representation, which allows number, 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.