TS
Frontend

TypeScript Generics and Utility Types

Mayur Dabhi
Mayur Dabhi
May 27, 2026
14 min read

You write a small helper like fetchJson(url) or first(arr). It has to work with users, products and plain strings, and the quickest way to make the compiler stop complaining is to type it as any. It works. Then a few weeks later someone calls .toUpperCase() on a number that came out of it, TypeScript says nothing, and the bug shows up in production instead of in your editor.

Generics fix exactly that, and utility types like Partial, Pick and Omit save you from copy-pasting the same interface five times with small changes. This post starts with why generics exist, then covers constraints, conditional and mapped types, writing your own utility types, and a few patterns I actually use: API response wrappers, a base repository and a generic React component.

What Are TypeScript Generics?

Without generics, a reusable function forces an uncomfortable tradeoff. Take an identity function, one that just returns whatever you pass it. Without generics, you'd write it like this:

TypeScript: without generics
// Option 1: Use a specific type (not reusable)
function identityNumber(arg: number): number {
    return arg;
}

// Option 2: Use any (no type safety at all)
function identity(arg: any): any {
    return arg;
}

const result = identity(42);
// TypeScript thinks result is `any`, so all type info is lost
result.toUpperCase(); // No error, but this will crash at runtime!

any switches type checking off for that value. You lose autocomplete, safe renames and compile-time errors, and it spreads: anything you derive from an any is also any. Generics solve this with a type parameter, a placeholder that gets filled in with the real type at each call site.

TypeScript: with generics
// Generic identity function. T is the type parameter
function identity<T>(arg: T): T {
    return arg;
}

// TypeScript infers T = number
const num = identity(42);          // type: number
const str = identity("hello");     // type: string
const arr = identity([1, 2, 3]);   // type: number[]

// You can also explicitly pass the type
const explicit = identity<boolean>(true); // type: boolean

// Generic function with array
function firstElement<T>(arr: T[]): T | undefined {
    return arr[0];
}

const first = firstElement([10, 20, 30]); // type: number
const word = firstElement(["a", "b"]);    // type: string
How to think about it

A type parameter is a variable for types instead of values. TypeScript usually infers it from the arguments, so you rarely write identity<string>(...) by hand. If you keep having to pass it explicitly, the signature probably isn't giving the compiler enough to infer from.

Input Value T = string type inferred Generic Function identity<T> (arg: T): T type preserved Output T still string ✓ Type information flows through the generic function unchanged

How generics preserve type information through a function

Generic Functions and Interfaces

You're not limited to one type parameter. You can have several, put them on interfaces, and give them defaults.

Multiple Type Parameters

TypeScript: multiple type parameters
// Pair function with two type parameters
function pair<A, B>(first: A, second: B): [A, B] {
    return [first, second];
}

const p1 = pair(1, "one");         // [number, string]
const p2 = pair(true, { x: 10 }); // [boolean, { x: number }]

// Swap function
function swap<A, B>(tuple: [A, B]): [B, A] {
    return [tuple[1], tuple[0]];
}

const swapped = swap(["hello", 42]); // [number, string]

Generic Interfaces

Interfaces take type parameters too. This is where generics start paying off in a real app: one Repository<T> or PaginatedResponse<T> instead of a near-identical copy per model.

TypeScript: generic interfaces
// Generic Repository interface
interface Repository<T> {
    findById(id: number): Promise<T | null>;
    findAll(): Promise<T[]>;
    create(data: Omit<T, 'id'>): Promise<T>;
    update(id: number, data: Partial<T>): Promise<T>;
    delete(id: number): Promise<void>;
}

// Generic paginated response; default type is unknown
interface PaginatedResponse<T = unknown> {
    data: T[];
    total: number;
    page: number;
    perPage: number;
    totalPages: number;
    hasNext: boolean;
    hasPrev: boolean;
}

// Usage
const usersPage: PaginatedResponse<User> = {
    data: [...],
    total: 250,
    page: 1,
    perPage: 20,
    totalPages: 13,
    hasNext: true,
    hasPrev: false
};

// Generic arrow function syntax (note the trailing comma to avoid JSX ambiguity)
const wrap = <T,>(value: T): { value: T } => ({ value });

If you're new to this, I'd learn it in roughly this order:

1

Start with Simple Type Parameters

Write generic identity functions and wrappers. Get comfortable with the <T> syntax and understand how TypeScript infers the type from the argument.

2

Add Constraints with extends

Use T extends SomeType to restrict which types are allowed, so you can safely access properties and methods on the generic value.

3

Learn the Built-in Utility Types

Learn Partial, Pick, Omit, Record, and the rest. You'll use these far more often than you'll write your own generics.

4

Create Custom Utility Types

Combine conditional types, mapped types, and infer to build the type transformations your codebase keeps needing.

Generic Constraints

A fully open T can be anything, so TypeScript won't let you touch any property on it. Often you want "any type, as long as it has a length" or "any key that actually exists on this object". That's what extends does in a type parameter list.

The extends Keyword

TypeScript: generic constraints
// Without constraint, TypeScript doesn't know T has .length
function logLength<T>(arg: T): T {
    console.log(arg.length); // Error: Property 'length' does not exist on type 'T'
    return arg;
}

// With constraint: T must have a length property
function logLength<T extends { length: number }>(arg: T): T {
    console.log(arg.length); // OK!
    return arg;
}

logLength("hello");       // OK, strings have .length
logLength([1, 2, 3]);     // OK, arrays have .length
logLength({ length: 5 }); // OK, object matches the shape
logLength(42);            // Error: numbers don't have .length

// keyof constraint: get a property safely
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
    return obj[key];
}

const user = { name: "Mayur", age: 28, email: "m@example.com" };
const name = getProperty(user, "name");   // type: string
const age  = getProperty(user, "age");    // type: number
// getProperty(user, "phone");            // Error: "phone" not in keyof typeof user

Conditional Types

Conditional types are if/else for types. The syntax T extends U ? X : Y reads as: "If T is assignable to U, the type is X; otherwise it's Y."

TypeScript: conditional types
// Basic conditional type
type IsString<T> = T extends string ? true : false;

type A = IsString<string>; // true
type B = IsString<number>; // false

// Extract the element type from an array using infer
type ArrayElement<T> = T extends (infer U)[] ? U : never;

type NumEl  = ArrayElement<number[]>;  // number
type StrEl  = ArrayElement<string[]>;  // string
type Never  = ArrayElement<string>;    // never (not an array)

// Unwrap a Promise
type Awaited<T> = T extends Promise<infer U> ? U : T;

type Resolved = Awaited<Promise<string>>; // string
type Direct   = Awaited<number>;           // number (not a promise)

// Non-nullable type
type NonNullable<T> = T extends null | undefined ? never : T;

type Safe = NonNullable<string | null | undefined>; // string
Common Pitfall

Over-constraining generics defeats the point. Only add a constraint when you actually need a specific property on the generic type. If you keep piling them on, a plain concrete type or a union is probably the better fit. Also, the Awaited and NonNullable above are re-implementations for learning; both already ship with TypeScript. Declare them in a file with no imports or exports (a global script) and you'll get Duplicate identifier 'Awaited'. Use the built-ins in real code.

Built-in TypeScript Utility Types

TypeScript ships with a set of utility types that turn one type into another. Most of the time you'll reach for these rather than writing generics yourself, especially when defining request and response shapes.

Utility Type Purpose Example Usage
Partial<T> Makes all properties optional Update DTOs, patch requests
Required<T> Makes all properties required Ensure fully-populated objects
Readonly<T> Makes all properties read-only Immutable config objects
Pick<T, K> Select a subset of keys from T Public-facing DTOs
Omit<T, K> Remove specific keys from T Exclude sensitive fields
Record<K, V> Map keys K to values of type V Dictionaries and lookup maps
Exclude<T, U> Remove U from a union type T Filter union members
NonNullable<T> Remove null and undefined from T Assert value is present
ReturnType<T> Extract the return type of a function Infer API response shapes

Here they are applied to one User interface, so you can compare the results side by side:

TypeScript: utility types in practice
interface User {
    id: number;
    name: string;
    email: string;
    password: string;
    createdAt: Date;
}

// Partial: for PATCH/update requests (all fields optional)
type UpdateUserDto = Partial<User>;
// { id?: number; name?: string; email?: string; ... }

// Pick: select only the fields you need
type UserPreview = Pick<User, 'id' | 'name' | 'email'>;
// { id: number; name: string; email: string }

// Omit: remove sensitive fields before sending to client
type PublicUser = Omit<User, 'password'>;
// { id: number; name: string; email: string; createdAt: Date }

// Omit for creation: id and createdAt are generated server-side
type CreateUserDto = Omit<User, 'id' | 'createdAt'>;
// { name: string; email: string; password: string }

// Record: map string keys to role values
type UserRoles = Record<string, 'admin' | 'user' | 'moderator'>;
// { [key: string]: 'admin' | 'user' | 'moderator' }
const roles: UserRoles = {
    "user_123": "admin",
    "user_456": "user",
};

// ReturnType: infer the return type of an existing function
async function getUser(id: number): Promise<User> {
    return fetch(`/api/users/${id}`).then(r => r.json());
}
type GetUserReturn = Awaited<ReturnType<typeof getUser>>;
// User

// Readonly: prevent mutation
const config: Readonly<{ apiUrl: string; timeout: number }> = {
    apiUrl: "https://api.example.com",
    timeout: 5000,
};
// config.apiUrl = "other"; // Error: Cannot assign to 'apiUrl' because it is a read-only property

Creating Custom Utility Types

The built-ins cover most cases, but sooner or later you'll want a transformation they don't offer. Mapped types and conditional types are enough to build it yourself.

Gotcha: Omit on a union

Omit isn't distributive. If Shape = Circle | Square, then Omit<Shape, 'id'> only keeps the keys both members have in common, and your discriminated union quietly collapses. You usually find out when TypeScript says Property 'radius' does not exist on something that clearly has one. The fix is a distributive version: type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;

DeepPartial: a Recursive Partial

The built-in Partial<T> only makes top-level properties optional. For nested config objects you need a recursive version. One caveat: T[K] extends object is also true for Date, arrays and functions, so this simple version recurses into those too. If your type contains them, check for them before the recursive branch.

TypeScript: DeepPartial custom utility
// Built-in Partial only goes one level deep
type Partial<T> = {
    [K in keyof T]?: T[K]; // Maps over each key, making it optional
};

// DeepPartial: recursively applies Partial to nested objects
type DeepPartial<T> = {
    [K in keyof T]?: T[K] extends object ? DeepPartial<T[K]> : T[K];
};

interface AppConfig {
    server: {
        host: string;
        port: number;
        ssl: {
            enabled: boolean;
            cert: string;
        };
    };
    database: {
        url: string;
        poolSize: number;
    };
}

// With built-in Partial, you'd have to provide the full server object
// With DeepPartial, every nested property is also optional
type PartialConfig = DeepPartial<AppConfig>;

const partial: PartialConfig = {
    server: {
        port: 8080  // ssl and host can be omitted
    }
    // database can be omitted entirely
};

Nullable, KeysOfType, and More

TypeScript: more custom utility types
// Simple nullable shorthand
type Nullable<T> = T | null;

const userId: Nullable<number> = null; // OK

// KeysOfType: get keys of T whose values are of type V
// Useful for extracting all string fields, all numeric fields, etc.
type KeysOfType<T, V> = {
    [K in keyof T]-?: T[K] extends V ? K : never;
}[keyof T];

interface Product {
    id: number;
    name: string;
    price: number;
    description: string;
    inStock: boolean;
}

type StringKeys  = KeysOfType<Product, string>;  // 'name' | 'description'
type NumberKeys  = KeysOfType<Product, number>;  // 'id' | 'price'
type BooleanKeys = KeysOfType<Product, boolean>; // 'inStock'

// MakeRequired: make specific keys required while keeping others as-is
type MakeRequired<T, K extends keyof T> = T & Required<Pick<T, K>>;

interface DraftPost {
    title?: string;
    body?: string;
    tags?: string[];
    publishedAt?: Date;
}

// To publish, title and body must be present
type PublishedPost = MakeRequired<DraftPost, 'title' | 'body'>;
// title: string (required), body: string (required), tags?: string[], publishedAt?: Date

Every custom utility above is a mapped type underneath. The pattern [K in keyof T]?: ... iterates over every key in T, and you can transform both the key (using as remapping) and the value type:

TypeScript: mapped type anatomy
// Anatomy of a mapped type:
// [K in keyof T]    iterate over all keys of T
// ?:                 make the property optional (remove with -?)
// T[K]              preserve the original value type

// Example: Convert all values to strings (getter pattern)
type Stringify<T> = {
    [K in keyof T]: string;
};

// Example: Add a prefix to all keys using key remapping (TS 4.1+)
type PrefixKeys<T, Prefix extends string> = {
    [K in keyof T as `${Prefix}${Capitalize<string & K>}`]: T[K];
};

interface User { name: string; email: string; }
type PrefixedUser = PrefixKeys<User, 'user'>;
// { userName: string; userEmail: string }

Real-World Applications

Here are three patterns where generics earn their keep in application code, not only in libraries.

API Response Wrapper

Most APIs wrap data in the same envelope every time. A generic wrapper means you describe that envelope once and get typed data all the way to the UI. Keep in mind that response.json() returns any, so the T here is a promise you're making to the compiler, not something checked at runtime. If the backend changes shape, TypeScript won't catch it; validate at the boundary (with something like Zod) if that matters.

TypeScript: generic API response types
// Generic API response wrapper
interface ApiResponse<T> {
    data: T;
    status: number;
    message: string;
    timestamp: string;
}

// Result type for error handling (similar to Rust's Result)
type ApiResult<T> =
    | { success: true;  data: T;      error: null }
    | { success: false; data: null;   error: string };

// Generic fetch helper
async function apiFetch<T>(url: string): Promise<ApiResult<T>> {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            return { success: false, data: null, error: `HTTP ${response.status}` };
        }
        const json: ApiResponse<T> = await response.json();
        return { success: true, data: json.data, error: null };
    } catch (err) {
        return { success: false, data: null, error: String(err) };
    }
}

// Usage: fully typed
const result = await apiFetch<User[]>('/api/users');
if (result.success) {
    result.data.forEach(user => console.log(user.name)); // user: User, fully typed
} else {
    console.error(result.error);
}

Generic Repository Pattern

TypeScript: abstract generic repository
// Base entity constraint: must have an id
interface Entity {
    id: number;
}

// Abstract generic base repository
abstract class BaseRepository<T extends Entity> {
    protected abstract tableName: string;
    protected items: T[] = [];

    findById(id: number): T | undefined {
        return this.items.find(item => item.id === id);
    }

    findAll(): T[] {
        return [...this.items];
    }

    create(data: Omit<T, 'id'>): T {
        const newItem = { ...data, id: this.items.length + 1 } as T;
        this.items.push(newItem);
        return newItem;
    }

    update(id: number, data: Partial<Omit<T, 'id'>>): T | undefined {
        const index = this.items.findIndex(item => item.id === id);
        if (index === -1) return undefined;
        this.items[index] = { ...this.items[index], ...data };
        return this.items[index];
    }

    delete(id: number): boolean {
        const index = this.items.findIndex(item => item.id === id);
        if (index === -1) return false;
        this.items.splice(index, 1);
        return true;
    }
}

// Concrete repository: just extend and specify the type
class UserRepository extends BaseRepository<User> {
    protected tableName = 'users';

    findByEmail(email: string): User | undefined {
        return this.items.find(u => u.email === email);
    }
}

const userRepo = new UserRepository();
const newUser = userRepo.create({ name: "Mayur", email: "m@example.com", password: "hashed", createdAt: new Date() });
// newUser is fully typed as User

React Generic Component

In React, generics let one component work with any option type while keeping callbacks like onChange typed to that option:

TypeScript: generic React Select component
import React from 'react';

interface SelectProps<T> {
    options: T[];
    value: T | null;
    onChange: (value: T) => void;
    getLabel: (option: T) => string;
    getValue: (option: T) => string | number;
    placeholder?: string;
}

// Generic Select: works with any option type
function Select<T,>({ options, value, onChange, getLabel, getValue, placeholder }: SelectProps<T>) {
    return (
        <select
            value={value ? String(getValue(value)) : ''}
            onChange={(e) => {
                const selected = options.find(o => String(getValue(o)) === e.target.value);
                if (selected) onChange(selected);
            }}
        >
            {placeholder && <option value="">{placeholder}</option>}
            {options.map(option => (
                <option key={String(getValue(option))} value={String(getValue(option))}>
                    {getLabel(option)}
                </option>
            ))}
        </select>
    );
}

// Usage with User objects
<Select<User>
    options={users}
    value={selectedUser}
    onChange={setSelectedUser}
    getLabel={(u) => u.name}
    getValue={(u) => u.id}
    placeholder="Select a user"
/>

// Usage with plain strings: same component, different type
<Select<string>
    options={['admin', 'user', 'moderator']}
    value={selectedRole}
    onChange={setSelectedRole}
    getLabel={(r) => r}
    getValue={(r) => r}
/>
Concrete Type User, Product Type Parameter T Generic Container Repository<T> ApiResponse<T> Select<T> Type-safe Output ✓ How concrete types flow through generic containers to produce type-safe outputs

Generic type flow: from concrete type to type-safe output

When I'd Reach for Generics (and When I Wouldn't)

Generics are worth it when the same logic really does run over different types and you want the caller's type to come back out: data fetching helpers, repositories, form and table components, collection utilities. Utility types are worth it almost anywhere you'd otherwise hand-copy an interface, because a copied interface drifts the moment someone adds a field to the original.

Where I'd hold back

  • A type parameter used only once. function log<T>(x: T): void gains nothing over x: unknown. If T doesn't link an input to an output or to another parameter, drop it.
  • Clever type-level code in app code. A five-level conditional type might be correct, but its error messages are unreadable and the next person on the team will be scared to touch it. Library authors pay that cost for their users. Most apps shouldn't.
  • Treating generics as validation. apiFetch<User[]>() doesn't check anything at runtime. It only tells the compiler to trust you.
  • Slow editors. Deeply recursive types like DeepPartial on big objects can make the language server sluggish, and in bad cases you'll see Type instantiation is excessively deep and possibly infinite. That's a sign to simplify the type, not to sprinkle in more casts.

A practical place to start: search your codebase for : any in helper functions and see which ones are really "same type in, same type out". Those are usually a one-line change to a type parameter.

TypeScript Generics Advanced Utility Types Frontend Type Safety
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.