TypeScript Course
TypeScript
/
Advanced

Live Coding: Advanced Generics

Definition

The toughest tier of TS interview questions, usually requiring the implementation of advanced utility types from scratch using Mapped Types, Conditional Types, and `infer`.

Explain Like I'm New

The interviewer says: 'Don't use the built-in `Omit` utility. Write your own custom version of `Omit` from absolute scratch.'

Real World Example

Writing a `DeepPartial<T>` utility that makes all properties, and all nested properties inside objects infinitely deep, optional.

Common Use Cases

  • •Deep type-system mastery
  • •Library authoring

Interactive Example

// INTERVIEW QUESTION:
// Implement 'DeepPartial', which makes all nested object properties optional.

type DeepPartial<T> = {
  // 1. Loop through all keys
  // 2. Add '?' to make the current key optional
  [K in keyof T]?:
    // 3. Condition: Is the property an object (and not an array/function)?
    T[K] extends object 
      ? DeepPartial<T[K]> // 4. YES: Recursively call DeepPartial on it!
      : T[K]              // 5. NO: Just return the base primitive type
};

interface Config {
  theme: string;
  api: {
    url: string;
    retries: number;
  };
}

// If we used normal Partial<Config>, 'api' would be optional, 
// but if provided, 'url' and 'retries' would still be strictly required.

const myConfig: DeepPartial<Config> = {
  api: {
    // Valid! 'retries' is omitted safely because DeepPartial drilled down into 'api'
    url: "https://api.com"
  }
};

Interview Questions

basic

  • Re-implement the `Pick` utility type.

intermediate

  • Implement a `DeepPartial` utility type.

advanced

  • Implement a `TupleToObject` type that converts an array like `['a', 'b']` to `{ a: 'a', b: 'b' }`.

Flash Cards

Question

How to implement Pick from scratch?

Click to reveal answer
Answer

`type MyPick<T, K extends keyof T> = { [P in K]: T[P] };`. It maps over the requested keys, and reaches into T to grab the corresponding value type.