Working with UUID in TypeScript: A Complete Guide

Recently, I was working on a project that required generating unique identifiers for user records in my TypeScript application.

The issue is… TypeScript doesn’t have a built-in UUID generator. So we need a reliable solution to implement this functionality.

In this article, I’ll cover several simple ways you can generate and work with UUIDs in TypeScript (including npm packages and browser-based solutions). So let’s dive in!

What is a UUID in TypeScript?

UUID (Universally Unique Identifier) is a 128-bit identifier that’s virtually guaranteed to be unique. It typically appears as follows: 123e4567-e89b-12d3-a456-426614174000.

UUIDs are perfect for generating unique IDs without a central coordination system. I use them in my applications for:

  • Database primary keys
  • Session identifiers
  • Transaction IDs
  • Unique file names
  • Client-side temporary IDs before server synchronization

Method 1: Using the uuid Package in TypeScript

The most common approach is to use the popular uuid npm package:

// First, install the package
// npm install uuid
// npm install @types/uuid --save-dev

import { v4 as uuidv4 } from 'uuid';

// Generate a UUID
const id: string = uuidv4();
console.log(id); // Output: something like '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

// Usage example: Creating a new user with a UUID
interface User {
  id: string;
  name: string;
  email: string;
}

function createUser(name: string, email: string): User {
  return {
    id: uuidv4(),
    name,
    email
  };
}

const newUser = createUser('John Smith', 'john@example.com');
console.log(newUser);
UUID in TypeScript

The uuid package offers several UUID versions:

  • v1(): Time-based UUID
  • v3(): Namespace UUID with MD5 hash
  • v4(): Random UUID (most common)
  • v5(): Namespace UUID with SHA-1 hash

For most applications, I recommend v4() as it provides a good balance of uniqueness and randomness.

Method 2: Using the crypto.randomUUID() in Modern Browsers in TypeScript

If you’re building a browser-based application and don’t want to add another dependency, you can use the built-in crypto.randomUUID() method that’s available in modern browsers:

function generateUUID(): string {
  if (typeof crypto !== 'undefined' && crypto.randomUUID) {
    return crypto.randomUUID();
  }

  throw new Error('crypto.randomUUID is not supported in this environment');
}

try {
  const id = generateUUID();
  console.log(id);
} catch (error) {
  console.error('Failed to generate UUID:', error);
  // Fall back to another method or library
}

This approach is perfect for modern web applications, but be aware that it’s not supported in older browsers, so you may need a fallback solution.

crypto.randomUUID() in Modern Browsers in TypeScript

Method 3: Implementing Your Own UUID Generator in TypeScript

Sometimes, you might want to avoid additional dependencies. Here’s a simple TypeScript implementation of a UUID v4 generator:

function generateUUIDv4(): string {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0;
    const v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

const id = generateUUIDv4();
console.log(id); // Output: something like '7daf8546-0969-4d7c-8fc8-4e144aba195f'

This implementation is lightweight but less robust than dedicated libraries. I typically only use this for prototyping or when package size is a critical concern.

Implement Own UUID Generator in TypeScript

Method 4: Using nanoid as a Lightweight Alternative in TypeScript

If you’re concerned about bundle size, nanoid is an excellent alternative to the uuid package:

// Install nanoid
// npm install nanoid
// npm install @types/nanoid --save-dev

import { nanoid } from 'nanoid';

const id = nanoid(); // By default produces a 21-character ID
console.log(id); // Something like "V1StGXR8_Z5jdHi6B-myT"

// You can also specify the length
const shortId = nanoid(10);
console.log(shortId); // Something like "IRFa-VaY2b"

// For URL-friendly IDs
import { customAlphabet } from 'nanoid';
const urlAlphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nanoidUrl = customAlphabet(urlAlphabet, 10);
const urlId = nanoidUrl(); 
console.log(urlId); // Something like "A4BcDe5fGh"

While nanoid doesn’t generate standard UUIDs, it creates secure, unique identifiers that are often sufficient for most applications and come with a much smaller package size.

nanoid as a Lightweight Alternative in TypeScript

TypeScript Type Definitions for UUIDs

To improve type safety, you can create a custom type for UUIDs:

// Define a UUID type
type UUID = string;

// Use it in your interfaces
interface Document {
  id: UUID;
  title: string;
  content: string;
}

// Function that accepts a UUID
function getDocument(id: UUID): Document | undefined {
  // Implementation here
  return {
    id,
    title: "Sample Document",
    content: "This is a sample document"
  };
}

// Generate and use a UUID
import { v4 as uuidv4 } from 'uuid';
const documentId: UUID = uuidv4();
const document = getDocument(documentId);

For even stronger type safety, you could use branded types:

// Create a branded type for UUID
type UUID = string & { readonly _brand: unique symbol };

// Function to create a UUID with the correct type
function createUUID(id: string): UUID {
  return id as UUID;
}

// Generate a UUID with the right type
import { v4 as uuidv4 } from 'uuid';
const id: UUID = createUUID(uuidv4());

This approach prevents regular strings from being used where UUIDs are expected, which can catch bugs at compile time.

TypeScript Type Definitions for UUIDs

Validating UUIDs in TypeScript

When working with UUIDs, it’s often necessary to validate them:

function isValidUUID(id: string): boolean {
  const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return uuidRegex.test(id);
}

// Test the function
console.log(isValidUUID('123e4567-e89b-12d3-a456-426614174000')); // true
console.log(isValidUUID('not-a-uuid')); // false

// You can also use the validate function from the uuid package
import { validate } from 'uuid';
console.log(validate('123e4567-e89b-12d3-a456-426614174000')); // true

I’ve found validation particularly important when accepting UUIDs from API requests or URL parameters.

Validating UUIDs in TypeScript

Conclusion

I hope you found this article helpful. Working with UUIDs in TypeScript is straightforward once you understand the available options. For most production applications, I recommend using the uuid package as it’s well-maintained, reliable, and offers multiple UUID versions. If you’re concerned about bundle size, nanoid provides a great alternative.

Remember that UUIDs are meant to be unique but not necessarily unpredictable or secure against guessing. If you need IDs that are both unique and cryptographically secure, consider additional security measures.

Other TypeScript articles you may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.