-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
4179answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English
Description
4179 - Flip
Flipping an object (that is, exchanging object values and keys) is a tricky proposition because an object only allows keys to be strings or symbols. TypeScript loosens this a bit by allowing number keys (which is a bit of a lie... but I digress). Somehow, we're going to need to figure out how to allow this kind of transposition.
🎥 Video Explanation
🔢 Code
// ============= Test Cases =============
import type { Equal, Expect, NotEqual } from './test-utils'
type A1 = Flip<{ pi: 'a' }>;
type B1 = { a: 'pi' };
type C1 = Expect<Equal<A1, B1>>;
type A2 = Flip<{ pi: 3.14; bool: true }>;
type B2 = { 3.14: 'pi'; true: 'bool' };
type C2 = Expect<Equal<A2, B2>>;
type A3 = Flip<{ prop: 'val'; prop2: 'val2' }>;
type B3 = { val2: 'prop2'; val: 'prop' };
type C3 = Expect<Equal<A3, B3>>;
type A4 = Flip<{ pi: 'a' }>;
type B4 = { b: 'pi' };
type C4 = Expect<NotEqual<A4, B4>>
// ============= Your Code Here =============
type Flip<
T extends Record<PropertyKey, string | number | boolean>
> = {
[P in keyof T as `${T[P]}`]: P;
};
// ============== Alternatives ==============
// not the best.. Record<any, any>
type Flip<T extends Record<any, any>> = {
[key in keyof T as `${T[key]}`]: key;
};
// a little better using PropertyKey
type Flip<T extends Record<PropertyKey, any>> = {
[P in keyof T as
T[P] extends PropertyKey
? T[P]
: `${T[P]}`
]: P
};➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
4179answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English