Skip to main content

Lesson 7 of 8

Mini Project: Task Manager - Part 5 (Advanced Type Utilities)

Apply advanced TypeScript types to the Task Manager - build a typed event system using template literal types, a DeepPartial update utility for nested patches, a typed field setter with indexed access, and a validation schema builder using mapped types.

17 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Task Manager Part 5 - Type Utility Library

Task Manager Part 5 - Type Utility Library
// src/types/utils.ts - reusable type utilities

// ── DeepPartial - recursive partial for nested updates ────────
export type DeepPartial<T> = {
  [K in keyof T]?: T[K] extends (infer U)[]
    ? DeepPartial<U>[]
    : T[K] extends object
    ? DeepPartial<T[K]>
    : T[K];
};

// ── DeepReadonly - freeze nested objects ─────────────────────
export type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K];
};

// ── Branded types - prevent ID mix-ups ───────────────────────
type Brand<T, B extends string> = T & { readonly __brand: B };
export type TaskId  = Brand<number, "TaskId">;
export type UserId  = Brand<number, "UserId">;

// Safe factory functions:
export const taskId  = (n: number): TaskId  => n as TaskId;
export const userId  = (n: number): UserId  => n as UserId;

// deleteTask(userId(1));   // ❌ Type error: UserId is not TaskId!
// deleteTask(taskId(1));   // ✅

// ── Typed event bus ────────────────────────────────────────────
type TaskManagerEvents = {
  "task:created":    { task: Task };
  "task:updated":    { taskId: TaskId; changes: Partial<Task> };
  "task:completed":  { taskId: TaskId; completedAt: Date };
  "task:deleted":    { taskId: TaskId };
  "user:assigned":   { taskId: TaskId; userId: UserId };
  "user:unassigned": { taskId: TaskId };
};

type EventName    = keyof TaskManagerEvents;          // all event names
type EventPayload<E extends EventName> = TaskManagerEvents[E];  // indexed access

class EventBus {
  private listeners: {
    [K in EventName]?: Array<(payload: TaskManagerEvents[K]) => void>;
  } = {};

  on<E extends EventName>(
    event: E,
    listener: (payload: EventPayload<E>) => void,
  ): this {
    (this.listeners[event] ??= []).push(listener as never);
    return this;
  }

  emit<E extends EventName>(event: E, payload: EventPayload<E>): void {
    this.listeners[event]?.forEach((l) => (l as (p: typeof payload) => void)(payload));
  }
}

// Usage - fully typed:
const bus = new EventBus();
bus.on("task:completed", ({ taskId, completedAt }) => {
  console.log(`Task ${taskId} done at ${completedAt.toISOString()}`);
});
// bus.emit("task:completed", { taskId: "wrong" });  // ❌ Error

// ── Typed patch builder ───────────────────────────────────────
function patch<T extends object>(
  original: T,
  changes: DeepPartial<T>,
): T {
  return { ...original, ...(changes as Partial<T>), updatedAt: new Date() } as T;
}

const updated = patch(existingTask, {
  status: "done",
  priority: "critical",
});   // Type: Task  ✅

Common Mistakes

  • Using `number` for IDs across domain objects - `deleteTask(someUserId)` silently compiles without branded types. Branded types prevent this class of bug with zero runtime cost.
  • Implementing `DeepPartial` without handling arrays - a naive `DeepPartial` treats arrays as objects and makes their element properties optional. Handle arrays explicitly with `T extends (infer U)[] ? DeepPartial<U>[] : ...`.
  • Building the event type map as a class with methods instead of a type - the type-only approach (`type TaskManagerEvents = {...}`) has zero runtime cost. The bus machinery is just the generic `on`/`emit` methods. Keep types separate from runtime code.

Tip

Tip

Practice Mini Project Task Manager Part 5 Advanced Type Utilities in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for Mini Project: Task Manager - Part 5 (Advanced Type Utilities)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Task Manager Part 5 Advanced Type Utilities from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Task Manager Part 5 Advanced Type Utilities is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.

Key Takeaways

  • Apply advanced TypeScript types to the Task Manager - build a typed event system using template literal types, a DeepPartial update utility for nested patches, a typed field setter with indexed access, and a validation schema builder using mapped types.
  • Using `number` for IDs across domain objects - `deleteTask(someUserId)` silently compiles without branded types. Branded types prevent this class of bug with zero runtime cost.
  • Implementing `DeepPartial` without handling arrays - a naive `DeepPartial` treats arrays as objects and makes their element properties optional. Handle arrays explicitly with `T extends (infer U)[] ? DeepPartial<U>[] : ...`.
  • Building the event type map as a class with methods instead of a type - the type-only approach (`type TaskManagerEvents = {...}`) has zero runtime cost. The bus machinery is just the generic `on`/`emit` methods. Keep types separate from runtime code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done