UUID Generator for TypeScript — Code Examples
Quick Answer: In modern TypeScript/JavaScript, use crypto.randomUUID() for UUID v4 -- it is built into all browsers and Node.js 19+, requires no dependencies. For UUID v7, use the uuid package: import { v7 } from "uuid".
FAQ
Do I need the uuid package in TypeScript?
For v4, no. crypto.randomUUID() is built-in. For v7, yes -- use the uuid package (npm install uuid @types/uuid) which supports v7 since version 9.
How do I type UUIDs in TypeScript?
Use a branded type: type UUID = string & { readonly __brand: unique symbol }. Or use template literals: type UUID = `${string}-${string}-${string}-${string}-${string}`.