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

11 - Tuple To Object (🎥 Video Explanation and Solution) #21514

@dimitropoulos

Description

@dimitropoulos

11 - Tuple To Object

TupleToObject is one of the more tricky challenges in the "easy" difficulty level. It teaches us how to remap tuples to other type structures, which is a skill that's going to come up quite a lot in many of the future challenges.

🎥 Video Explanation

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

Tuple To Object

🔢 Code

import type { Equal, Expect } from "./test-utils";

const tuple = [
  "tesla",
  "model 3",
  "model X",
  "model Y"
] as const;
type A1 = TupleToObject<typeof tuple>;
type B1 = {
  tesla: "tesla";
  "model 3": "model 3";
  "model X": "model X";
  "model Y": "model Y";
}
type C1 = Expect<Equal<A1, B1>>;

const tupleNumber = [1, 2, 3, 4] as const;
type A2 = TupleToObject<typeof tupleNumber>;
type B2 = { 1: 1; 2: 2; 3: 3; 4: 4 };
type C2 = Expect<Equal<A2, B2>>;

const tupleMix = [1, "2", 3, "4"] as const;
type A3 =TupleToObject<typeof tupleMix>;
type B3 = { 1: 1; "2": "2"; 3: 3; "4": "4" };
type C3 = Expect<Equal<A3, B3>>;

// @ts-expect-error(2344)
type E1 = TupleToObject<[[1, 2], {}]>;

// ============= Your Code Here =============
type TupleToObject<
  T extends readonly PropertyKey[] // also any[]
> = {
  [P in T[number]]: P;
};

type SameAsPropertyKey = keyof any;

➕ More Solutions

For more video solutions to other challenges: see the umbrella list! #21338

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions