UUID in TypeScript

TypeScript UUID Generator

The type system can do more here than string: the DOM lib already knows the exact shape randomUUID() returns.

Typed out of the boxNo @types neededBranded IDs

Generated locally with the Web Crypto API — nothing leaves your browser.

Generating UUIDs in TypeScript

How to generate

  1. Press Generate UUID above to mint a value in this browser — nothing is sent anywhere.
  2. Copy one value with Copy, or set How many and use Copy all for a fixture list.
  3. Switch Version if your code needs v7 instead of the v4 default, and turn on Formatting to match your stack's conventions.

Use Cases

How TypeScript UUID Generator Compares

crypto.randomUUID()Returns a hyphenated template literal type
stringNo structure, nothing stops a swap
Branded UUIDSame bytes, checked at compile time, zero runtime cost

Code Examples

TypeScript
// lib.dom.d.ts types this as `${string}-${string}-${string}-${string}-${string}`
const id = crypto.randomUUID();

// A nominal type, so a UserId can never be passed where an OrderId is wanted
type Brand<T, B extends string> = T & { readonly __brand: B };
export type UserId = Brand<string, 'UserId'>;

export const newUserId = (): UserId =>
  crypto.randomUUID() as UserId;
Validation
const UUID_RE =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

const isUuid = (v: string): boolean => UUID_RE.test(v);

Frequently Asked Questions

Do I need @types/uuid for TypeScript?
Not for crypto.randomUUID() — its declaration is part of the DOM lib. The uuid package ships its own types, so no separate @types install is needed there either.
How do I type an identifier that is definitely a UUID?
Use a branded type: intersect string with a unique marker property and cast once where the value is created. It is erased at runtime but rejected by the compiler everywhere else.
Why is my UUID typed as a template literal instead of string?
Recent DOM libs describe randomUUID() as five hyphen-joined string segments. That is what lets the compiler catch code that treats the value as a bare hex string.

Related tools