Skip to content

Type-Safe Config Manager

Easy ~15 min

What you'll build

A ConfigManager that merges default config with user overrides, where overrides are Partial<Config> and the result is Readonly<Config>.

Goals

  • Apply Partial, Required, and Readonly utility types
  • Merge configs with type safety
  • Prevent mutation of final config
  • Understand utility type composition

Prerequisites

  • Utility types
  • Interfaces
  • Object spread

Steps

  1. 1

    Define the config interface

    Create a Config interface with required fields. This is the complete shape of the configuration.

    Code
    interface Config {
      port: number;
      host: string;
      debug: boolean;
      maxConnections: number;
    }

    Expected result

    A Config interface with four required fields.

  2. 2

    Build the config manager

    Create a function that takes defaults (Config) and overrides (Partial<Config>), merges them, and returns Readonly<Config> to prevent mutation.

    Code
    function createConfig(
      defaults: Config,
      overrides: Partial<Config>
    ): Readonly<Config> {
      return Object.freeze({ ...defaults, ...overrides });
    }

    Expected result

    A function that merges configs and returns a frozen, readonly result.

  3. 3

    Use the config manager

    Create a config with defaults and partial overrides. The result is typed and immutable.

    Code
    const config = createConfig(
      { port: 3000, host: "localhost", debug: false, maxConnections: 10 },
      { port: 8080, debug: true }
    );
    console.log(config.port); // 8080
    // config.port = 4000; // Compile error: readonly

    Expected result

    Config is merged correctly and cannot be mutated at compile time or runtime.

  4. 4

    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.

  5. 5

    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.

Try it yourself

What you learned

You composed utility types to create a flexible, safe config system. Partial allows partial overrides, Readonly prevents mutation, and the spread merge is type-checked. This is how real-world config libraries like dotenv and convict work.

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