#4179Medium

Flip

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.

Challenge Instructions: Flip

Medium

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).

ChallengeSolution
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' }>>
  >,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

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:

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.

Share this challenge