CodeWithMihir

TypeScript Tutorial

TypeScript Generic Utility Patterns

Learn practical generic utility patterns in TypeScript, including wrappers, keyed access helpers, reusable responses, and safe object updates.

Welcome back! I am Mihir, and in this lesson we will learn practical generic utility patterns in TypeScript.

Generics become powerful when you use them to create small reusable helpers.


Wrapper Pattern

type ApiResponse<T> = {
  success: boolean;
  data: T;
  message?: string;
};

type User = {
  id: number;
  name: string;
};

const response: ApiResponse<User> = {
  success: true,
  data: {
    id: 1,
    name: "Mihir",
  },
};

The same wrapper can be reused for products, posts, comments, and more.


List Pattern

type ListResult<T> = {
  items: T[];
  total: number;
  page: number;
};

Usage:

type Product = {
  id: number;
  name: string;
};

const products: ListResult<Product> = {
  items: [{ id: 1, name: "Keyboard" }],
  total: 1,
  page: 1,
};

This is common in paginated APIs.


Keyed Access Pattern

function getValue<T, K extends keyof T>(object: T, key: K): T[K] {
  return object[key];
}

Usage:

const user = {
  id: 1,
  name: "Mihir",
  active: true,
};

const name = getValue(user, "name");
const active = getValue(user, "active");

TypeScript keeps the return type connected to the key.


Safe Update Pattern

function updateField<T, K extends keyof T>(
  object: T,
  key: K,
  value: T[K]
): T {
  return {
    ...object,
    [key]: value,
  };
}

Usage:

const updatedUser = updateField(user, "name", "Mihir Soni");

Invalid:

updateField(user, "active", "yes");

active expects a boolean, not a string.


Nullable Pattern

type Nullable<T> = T | null;

let selectedUser: Nullable<User> = null;

This is a small but useful helper when something can be missing.


Dictionary Pattern

type Dictionary<T> = {
  [key: string]: T;
};

const scores: Dictionary<number> = {
  mihir: 95,
  alex: 88,
};

Every string key has the same value type.


Quick Recap

  • Generic wrappers keep reusable structures type-safe.
  • T represents a flexible value type.
  • K extends keyof T is useful for safe object keys.
  • T[K] keeps value types connected to keys.
  • Small generic helpers can remove repeated type code.

Next up, we will learn Real-world Generic Examples →.