~/alexsh.blog

$ cat advanced-typescript/12-advanced-module-and-namespace-patterns.md

Advanced Module and Namespace Patterns

February 9, 20261 min readpart 12/20

Difficulty: Upper Intermediate. Prerequisites: ES modules, declaration files, declaration merging.

Advanced module patterns include ambient modules, wildcard declarations, path mapping, and sophisticated declaration file authoring. Essential for library authors and complex build systems.

Key concepts

  • Ambient module declarations for untyped packages
  • Wildcard module patterns for CSS/images
  • Path mapping in tsconfig
  • Package.json exports and types
  • Namespaces for organizing types

Example

codets
// Ambient modules
declare module 'untyped-lib' {
  export function doSomething(x: string): number;
}

// Wildcard modules
declare module '*.css' { const c: { [k: string]: string }; export default c; }
declare module '*.png' { const s: string; export default s; }

// Path mapping (tsconfig.json)
// "paths": { "@components/*": ["src/components/*"] }
import { Button } from '@components/Button';

// Namespace for grouping
export namespace API {
  export interface User { id: string; name: string }
  export namespace Requests {
    export interface Create { name: string; email: string }
  }
}
const u: API.User = { id: '1', name: 'Alice' };

// Real-world: Vite's client.d.ts types all asset imports with wildcard modules

Resources

Practice

Hints

  • Use "declare module" with wildcard patterns to type non-JS imports like CSS and images.
  • Path mapping in tsconfig.json lets you create clean import aliases.