这是indexloc提供的服务,不要输入任何密码
Skip to content

4179 - Flip (🎥 Video Explanation and Solution) #24323

@dimitropoulos

Description

@dimitropoulos

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

Release Date: 2023-03-04 19:00 UTC

Flip

🔢 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

No one assigned

    Labels

    4179answerShare answers/solutions to a questionenin English

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions