TypeScript Exclude and Extract in Depth: Filtering Union Types for Real API Contracts

This article was written with the assistance of AI, under human supervision and review.

TypeScript Exclude and Extract in Depth: Filtering Union Types for Real API Contracts

Most union type problems stem from treating them as static lists instead of transformable sets. Teams ship API route handlers that accept internal-only paths in public contexts, event systems that route admin actions to customer callbacks, and database queries that accidentally expose soft-deleted records. The compiler stays silent because these are all valid union members—just in the wrong context.

The failure mode here is subtle but expensive. A public API endpoint that accepts "/admin/users" | "/public/users" will happily receive admin routes at runtime. The type system sees no violation because both paths belong to the union. Tests pass. The security audit finds the hole six months later.