Skip to content

Generic Utility Library

Easy ~15 min

What you'll build

A utils.ts file with four generic functions that work with any type while preserving type safety through type parameters.

Goals

  • Write generic functions with type parameters
  • Use keyof and indexed access types
  • Preserve type relationships between inputs and outputs
  • Understand type inference from function arguments

Prerequisites

  • Generics basics
  • keyof operator
  • Arrays

Steps

  1. 1

    Write identity and pick

    identity returns its argument unchanged. pick extracts a single property from an object using keyof for type safety.

    Code
    function identity<T>(value: T): T { return value; }
    
    function pick<T, K extends keyof T>(obj: T, key: K): T[K] {
      return obj[key];
    }

    Expected result

    Two generic functions. pick is type-safe: pick({a: 1}, 'a') returns number.

  2. 2

    Write groupBy and unique

    groupBy partitions an array by a key function. unique removes duplicates. Both use generics to work with any element type.

    Code
    function groupBy<T, K extends string>(arr: T[], fn: (x: T) => K): Record<K, T[]> {
      return arr.reduce((acc, x) => {
        const key = fn(x);
        (acc[key] ||= []).push(x);
        return acc;
      }, {} as Record<K, T[]>);
    }
    
    function unique<T>(arr: T[]): T[] {
      return [...new Set(arr)];
    }

    Expected result

    Four generic utility functions that work with any type.

  3. 3

    Add type guards & runtime checks

    Write a user-defined type guard function to validate data shape at runtime, combined with the unknown type to safely handle external input. Type guards give TypeScript runtime type safety too.

    Code
    type User = { id: number; name: string };
    
    function isUser(value: unknown): value is User {
      if (typeof value !== "object" || value === null) return false;
      const obj = value as Record<string, unknown>;
      return typeof obj.id === "number" && typeof obj.name === "string";
    }
    
    // Usage with unknown input
    const data: unknown = JSON.parse(rawJson);
    if (isUser(data)) {
      console.log(data.name); // TS knows data is User here
    } else {
      console.error("Invalid user data");
    }

    Expected result

    When isUser returns true, TS narrows data to User type; invalid data goes to the else branch.

  4. 4

    Add generic utility functions

    Write generic utility functions (e.g., deepFreeze, groupBy) to enhance type-safe reuse. Generics let utility functions work with multiple types without losing type information.

    Code
    function groupBy<T, K extends string | number>(
      items: T[],
      keyFn: (item: T) => K
    ): Record<K, T[]> {
      const result = {} as Record<K, T[]>;
      for (const item of items) {
        const key = keyFn(item);
        (result[key] ??= []).push(item);
      }
      return result;
    }
    
    // Usage
    const byAge = groupBy(users, u => u.age);

    Expected result

    groupBy groups any array by key, returning a type-safe Record.

  5. 5

    Compile check & type tests

    Run tsc --noEmit to confirm no type errors; use expectTypeOf or @ts-expect-error comments for type-level tests. A clean compile is the acceptance criterion for TypeScript projects.

    Code
    // Run: npx tsc --noEmit
    
    // Type-level test with @ts-expect-error
    // @ts-expect-error — string is not a number
    const bad: number = "oops";
    
    // Correct usage compiles cleanly
    const good: number = 42;

    Expected result

    tsc --noEmit produces no errors; the @ts-expect-error line does error (and is suppressed).

Try it yourself

What you learned

You practiced writing generic functions where the type parameter T flows from input to output, preserving type information. The keyof constraint on pick ensures only valid property names can be used.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic