#2946Medium

ObjectEntries

Implement the type version of ```Object.entries``` Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement the type-level version of Object.entries, which converts an object type into a union of key-value tuple pairs while correctly handling optional and undefined properties.

Challenge Instructions: ObjectEntries

Medium

Implement the type version of Object.entries

For example

interface Model {
name: string;
age: number;
locations: string[] | null;
}
type modelEntries = ObjectEntries<Model> // ['name', string] | ['age', number] | ['locations', string[] | null];

Change the following code to make the test cases pass (no type check errors).

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

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

type cases = [
  Expect<Equal<ObjectEntries<Model>, ModelEntries>>,
  Expect<Equal<ObjectEntries<Partial<Model>>, ModelEntries>>,
  Expect<Equal<ObjectEntries<{ key?: undefined }>, ['key', undefined]>>,
  Expect<Equal<ObjectEntries<{ key: undefined }>, ['key', undefined]>>,
  Expect<
    Equal<
      ObjectEntries<{ key: string | undefined }>,
      ['key', string | undefined]
    >
  >,
]

Pro Challenge

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

One-time payment. Lifetime access.

Detailed Explanation

type ObjectEntries<T> = {
  [K in keyof Required<T>]: [K, Required<T>[K] extends never ? undefined : Required<T>[K]];
}[keyof T];

How it works:

An alternative approach using a distributive conditional:

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

This challenge helps you understand mapped types, optional property handling, and indexed access types, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge