TypeScript Course
TypeScript
/
Advanced

Scenario-Based TS Questions

Definition

Architectural interview questions that ask you to design the type system for a complex application feature.

Explain Like I'm New

Instead of writing algorithms, the interviewer asks: 'We are building a unified API client that talks to 5 different microservices. How do you design the Type Interfaces to ensure the frontend developers get perfect autocomplete for all 5 services without duplicating code?'

Real World Example

Designing the type system for a Redux-like state management library.

Common Use Cases

  • •Staff/Principal Engineering interviews
  • •System Design

Interactive Example

// SCENARIO: Design a strictly typed Event Emitter

// 1. The developer defines their app's specific events
type AppEvents = {
  'user_login': { userId: string, timestamp: number };
  'user_logout': void; // No payload
  'error': Error;
};

// 2. The generic class design
class TypedEventEmitter<Events extends Record<string, any>> {
  private listeners: any = {};

  // K is constrained to be a valid event name
  // The payload type dynamically updates based on K!
  on<K extends keyof Events>(
    event: K, 
    callback: (payload: Events[K]) => void
  ) {
    if (!this.listeners[event]) this.listeners[event] = [];
    this.listeners[event].push(callback);
  }

  emit<K extends keyof Events>(event: K, payload: Events[K]) {
    this.listeners[event]?.forEach((cb: any) => cb(payload));
  }
}

const emitter = new TypedEventEmitter<AppEvents>();

// TS enforces the payload must be an Error object!
emitter.emit('error', new Error("Crash!"));

// TS throws error: payload missing userId!
// emitter.emit('user_login', { timestamp: 123 });

Interview Questions

basic

  • How do you share types between a Node backend and a React frontend?

intermediate

  • How would you type a highly dynamic form generator based on JSON configuration?

advanced

  • Design the types for an Event Emitter class.

Flash Cards

Question

How do you share types between Backend/Frontend?

Click to reveal answer
Answer

Monorepo architectures (Nx, Turborepo). You create a third package called `@company/shared-types`. Both the backend and frontend install this local package. If the backend changes a DTO, the frontend compilation instantly fails, preventing production bugs.

Question

Design the types for an Event Emitter

Click to reveal answer
Answer

You need a Generic Map. `type EventMap = { 'login': User, 'logout': void }`. The emitter methods look like: `on<K extends keyof EventMap>(event: K, cb: (payload: EventMap[K]) => void)`.