Generating UUID in TypeScript

TypeScript is a strongly-typed programming language built on top of JavaScript, maintained and developed by Microsoft. It extends the capabilities of JavaScript by adding a type system, enabling developers to gain better tooling support in projects of any scale. The main advantage of TypeScript is its ability to capture errors and provide suggestions for fixes before the code runs, thereby accelerating development speed and improving code quality.

Through features like interfaces, type aliases, and generics, TypeScript allows developers to describe the shape of objects and functions, making it easier to view documentation and issues within editors. Additionally, TypeScript code is ultimately transpiled into JavaScript code, which runs in any environment that supports JavaScript, including browsers, Node.js or Deno, and various applications.

1. Using the Third-Party Library uuid

The uuid library is a widely used third-party library that can easily generate UUIDs in TypeScript projects. First, you need to install this library:

npm install uuid

Then, you can use it in your TypeScript code like this:

import { v4 as uuidv4 } from "uuid";

let myuuid = uuidv4();

console.out("Your UUID is: " + myuuid);

In this example, the v4 function generates a UUID based on random numbers (compliant with RFC 4122 version 4). The uuid library provides different versions of UUID generation functions, including v1, v3, v4, and v5.

Code Explanation

  • Line 1: Imports the function for generating Version 4 UUIDs. Additionally, functions for creating Version 1, 3, and 5 UUIDs are provided.

  • Line 3: A UUID is generated and stored in a variable named myuuid.

  • Line 5: Outputs a string in the format: "Your UUID is: 8a6e0804-2bd0-4672-b79d-d97027f9071a."

Note: The uuid JavaScript library is classified as a script type. Given its small footprint and general absence of custom type handling, it is not mandatory to include type definitions within a TypeScript project.

If you wish to install TypeScript definitions for the uuid JavaScript library, you can execute the following command:

npm install -D @types/uuid

The uuid library offers a variety of additional functionalities, such as converting between the string representation of a UUID and a byte array. For more information on the JavaScript uuid library, you can visit its GitHub page.

2. Using the Built-in crypto API

If you do not want to introduce external dependencies, you can use the Web Crypto API to generate a UUID. This method is available in Node.js and modern browsers:

function generateUUID(): string {
  const array = new Uint8Array(16);
  window.crypto.getRandomValues(array);
  // Returns a UUID in RFC 4122 version 4 format
  return (
    ((
      (array[6] & 0x0f) |
      (array[6] >> 4) |
      (0x40 * Math.random()) |
      (0x80 * Math.random())
    ).toString(16) +
      "-" +
      (array[8] & 0x3f)) |
    ((array[8] >> 6) + "-" + (array[8] & 0x0f)) |
    (0x40 * Math.random() + "-" + (array[9] & 0x3f)) |
    ((array[9] >> 6) +
      "-" +
      (array[9] & 0x0f).toString(16) +
      (array[10] & 0x0f).toString(16) +
      (array[11] & 0x0f).toString(16) +
      (array[12] & 0x0f).toString(16) +
      (array[13] & 0x0f).toString(16) +
      (array[14] & 0x0f).toString(16) +
      (array[15] & 0x0f).toString(16))
  );
}

const myUUID = generateUUID();
console.log(myUUID);

This code uses the crypto.getRandomValues() method to fill a 16-byte array and then performs bitwise operations on the array according to the UUID format to generate a UUID string that complies with RFC 4122 version 4.

3. Manually Implementing the UUID Generation Algorithm

If you need a deeper understanding of the UUID generation process or want to generate a UUID in an environment that does not support the crypto API, you can manually implement the UUID generation algorithm:

function generateUUIDv4(): string {
  let d = new Date().getTime(); // Get the current time
  const uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(
    /[xy]/g,
    function (c) {
      const r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
    }
  );
  return uuid;
}

const myUUID = generateUUIDv4();
console.log(myUUID);

In this function, we use a template string to construct the UUID and replace x and y with regular expressions to generate the correct hexadecimal values. The 4 is hardcoded in the third group to comply with the requirements of UUID version 4, and the y part is ensured to be valid by adding 0x3 and 0x8.