Generate a UUID in TypeScript
Generate, validate, and parse RFC 4122/9562 UUIDs in TypeScript with nominal branded types and runtime guards.
TypeScript brings compile-time type safety to UUIDs. By pairing runtime Web Crypto generation with nominal branded types and type guards, you can prevent accidental parameter swapping (such as passing a UserId where an OrderId is expected) while maintaining zero-overhead JavaScript compilation.
Quick Start#
The native Web Crypto API returns a typed string directly:
Creating Type-Safe Branded UUIDs#
In large codebases, treating all identifiers as generic string types frequently leads to subtle bugs where two different entities' IDs are swapped in function arguments:
Runtime Validation & Type Guards#
Use a custom type guard to refine untyped inputs (such as API route parameters or form submissions) into strongly typed UUID instances:
Using the uuid Package with TypeScript#
When using the uuid package, TypeScript types are bundled natively without requiring a separate @types package:
Parsing to Uint8Array for Database Adapters#
For low-level database operations (such as PostgreSQL binary UUID columns or MongoDB binary subtypes), convert string UUIDs to typed byte buffers:
Best Practices#
- Use Branded Types: Prevent accidental ID cross-assignment in domain models and services.
- Apply Type Guards at System Boundaries: Always validate incoming strings from HTTP requests or message queues before casting to branded UUID types.
- Adopt UUIDv7 for Database Keys: When using SQL databases with B-Tree indexes, UUIDv7 provides linear page-insertion performance without sacrificing distributed generation.