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

2946 - ObjectEntries (🎥 Video Explanation and Solution) #23749

@dimitropoulos

Description

@dimitropoulos

2946 - ObjectEntries

If you manage to complete this task, you will have greatly strengthened your understanding of how to "iterate" over specific object values. This one is a bit of a head-scratcher, but it's worth the trouble.

🎥 Video Explanation

Release Date: 2023-02-24 19:00 UTC

ObjectEntries

🔢 Code

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

interface Model {
  name: string
  age: number
  locations: string[] | null
}

type ModelEntries =
  | ['name', string]
  | ['age', number]
  | ['locations', string[] | null]

type A1 = ObjectEntries<Model>;
type B1 = ModelEntries;
type C1 = Expect<Equal<A1, B1>>;

type A2 = ObjectEntries<Partial<Model>>;
type B2 = ModelEntries;
type C2 = Expect<Equal<A2, B2>>;

type A3 = ObjectEntries<{ key?: undefined }>;
type B3 = ['key', undefined];
type C3 = Expect<Equal<A3, B3>>;

type A4 = ObjectEntries<{ key: undefined }>;
type B4 = ['key', undefined];
type C4 = Expect<Equal<A4, B4>>;

// ============= Your Code Here =============
type ObjectEntries<T, U extends keyof T = keyof T> =
  U extends unknown
  ? [
    U,
    T[U] extends (infer F | undefined)
      ? F
      : T[U]
    ]
  : [];

// ============== Alternatives ==============
// grabbing specific T values
type ObjectEntries<T> =
  keyof T extends infer P
  ? P extends keyof T
    ? [
        P,
        Required<T>[P] extends never
          ? undefined
          : Required<T>[P]
      ]
    : never
  : never;

// using storage
type ObjectEntries<
  T,
  R = Required<T>,
  K = keyof R
> =
  K extends keyof R
  ? [
      K,
      R[K] extends undefined
        ? undefined
        : R[K]
    ]
  : never

type RemoveUndefined<T> =
  [T] extends [undefined]
  ? T
  : Exclude<T, undefined>;
type ObjectEntries<T> = {
  [K in keyof T]-?: [K, RemoveUndefined<T[K]>]
}[keyof T]

// ================== NOPE ==================
// fails C3
type ObjectEntries<T, K = keyof T> =
  K extends keyof T
  ? [K, Required<T>[K]]
  : never

➕ 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