Skip to main content

Lesson 7 of 7

Mini Project: Task Manager - Part 3 (Generic Utilities & Guards)

Apply functions, generics, and type guards to the Task Manager - build a generic API response wrapper, typed fetch utility, type-safe task assertions, and a strongly-typed filtering pipeline.

16 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Task Manager Part 3 - Generic Utilities

Task Manager Part 3 - Generic Utilities
// src/types/api.ts
export interface ApiResponse<T> {
  success: boolean;
  data: T;
  meta?: {
    total: number;
    page: number;
    perPage: number;
  };
  error?: {
    code: string;
    message: string;
  };
}

export type ApiResult<T> =
  | { ok: true;  data: T }
  | { ok: false; error: string; statusCode: number };

// src/lib/apiClient.ts
// ── Generic typed fetch utility ───────────────────────────────
async function apiFetch<T>(
  path: string,
  guard: (value: unknown) => value is T,
): Promise<ApiResult<T>> {
  try {
    const res = await fetch(`/api${path}`);
    const json: unknown = await res.json();

    if (!res.ok) {
      const err = json as { message?: string };
      return { ok: false, error: err.message ?? "Request failed", statusCode: res.status };
    }

    if (!guard(json)) {
      return { ok: false, error: "Invalid response shape", statusCode: 500 };
    }

    return { ok: true, data: json };
  } catch (error: unknown) {
    return {
      ok: false,
      error: error instanceof Error ? error.message : "Network error",
      statusCode: 0,
    };
  }
}

// src/lib/guards.ts
import type { Task, User } from "../types/domain";

export function isTask(v: unknown): v is Task {
  return (
    typeof v === "object" && v !== null &&
    "id" in v && typeof (v as Task).id === "number" &&
    "title" in v && typeof (v as Task).title === "string" &&
    "status" in v && ["todo", "in-progress", "done", "archived"].includes((v as Task).status)
  );
}

export function isTaskArray(v: unknown): v is Task[] {
  return Array.isArray(v) && v.every(isTask);
}

// src/lib/filters.ts
// ── Generic reusable filter pipeline ─────────────────────────
type Predicate<T> = (item: T) => boolean;

function and<T>(...predicates: Predicate<T>[]): Predicate<T> {
  return (item) => predicates.every((p) => p(item));
}

function or<T>(...predicates: Predicate<T>[]): Predicate<T> {
  return (item) => predicates.some((p) => p(item));
}

function not<T>(predicate: Predicate<T>): Predicate<T> {
  return (item) => !predicate(item);
}

// Usage:
const isHighPriority   = (t: Task) => t.priority === "high" || t.priority === "critical";
const isActive         = (t: Task) => t.state.phase === "active";
const isNotAssigned    = (t: Task) => t.state.phase !== "active";

const urgentActiveTasks = tasks.filter(
  and(isHighPriority, isActive)
);
const unassignedOrDone = tasks.filter(
  or(isNotAssigned, (t) => t.state.phase === "completed")
);

// ── Usage in component / route ─────────────────────────────────
const result = await apiFetch("/tasks", isTaskArray);
if (result.ok) {
  const filtered = result.data.filter(and(isHighPriority, isActive));
  console.log("Urgent active tasks:", filtered.length);
} else {
  console.error("Failed to fetch tasks:", result.error);
}

Common Mistakes

  • Casting API responses with `as Task[]` - this silently accepts any malformed data. Use a real guard that checks actual property types and values.
  • Building predicates without a generic wrapper - if `and()` and `or()` aren't generic, they only work for `Task`. Generic combinators work for any domain type.
  • Not returning `ApiResult` from fetch utilities - returning the data directly forces callers to use try/catch. `ApiResult<T>` (or `Result<T, E>`) makes error handling explicit and typed.

Tip

Tip

Practice Mini Project Task Manager Part 3 Generic Utilities Guards 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 3 (Generic Utilities & Guards)

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Task Manager Part 3 Generic Utilities Guards 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 3 Generic Utilities Guards 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 functions, generics, and type guards to the Task Manager - build a generic API response wrapper, typed fetch utility, type-safe task assertions, and a strongly-typed filtering pipeline.
  • Casting API responses with `as Task[]` - this silently accepts any malformed data. Use a real guard that checks actual property types and values.
  • Building predicates without a generic wrapper - if `and()` and `or()` aren't generic, they only work for `Task`. Generic combinators work for any domain type.
  • Not returning `ApiResult` from fetch utilities - returning the data directly forces callers to use try/catch. `ApiResult<T>` (or `Result<T, E>`) makes error handling explicit and typed.

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/7 done