TypeScript Course
TypeScript
/
Intermediate

Utility Type Deep Dives

Definition

Interview questions focusing heavily on combining TS built-in utility types to solve complex architectural mapping requirements.

Explain Like I'm New

The interviewer will present a messy API response type and ask you to 'clean it up' using utilities like `Omit`, `Extract`, `NonNullable`, and `ReturnType` without rewriting the interfaces from scratch.

Real World Example

You have a `User` union `type User = Admin | Guest | Member`. The interviewer asks: 'Write a type that extracts ONLY the Admin and Member types, and removes the password field from both'.

Common Use Cases

  • •Refactoring legacy types
  • •Interview screening

Interactive Example

// INTERVIEW SCENARIO:
// You are given a massive Union of string logs.
// Extract only the Error logs, and then remove the timestamp.

type Logs = 
  | { type: 'INFO', msg: string, time: number }
  | { type: 'ERROR', code: number, time: number }
  | { type: 'WARNING', msg: string, time: number };

// Step 1: Use Extract to filter the Union based on a specific discriminant
type ErrorLogs = Extract<Logs, { type: 'ERROR' }>;

// Step 2: Use Omit to clean the object
type CleanError = Omit<ErrorLogs, 'time'>;

// Combined into one fluid, highly impressive step:
type ProcessedError = Omit<Extract<Logs, { type: 'ERROR' }>, 'time'>;

const err: ProcessedError = {
  type: 'ERROR',
  code: 500
  // time is strictly prohibited here now!
};

Interview Questions

basic

  • Combine `Omit` and `ReturnType` in a single statement.

intermediate

  • What is the difference between `Exclude` and `Omit`?

advanced

  • How do you create an `OmitByType` utility?

Flash Cards

Question

Exclude vs Omit?

Click to reveal answer
Answer

`Exclude` operates on UNION types (e.g., extracting 'a' from `'a'|'b'|'c'`). `Omit` operates on OBJECT types (e.g., removing the 'password' key from the `{ name, password }` interface).

Question

What is OmitByType?

Click to reveal answer
Answer

A custom utility that removes properties based on their VALUE type, not their key name. E.g., 'Remove all properties from this object that are booleans'. Uses mapped type remapping: `[K in keyof T as T[K] extends boolean ? never : K]: T[K]`.