Generate UUIDs in Typescript

Resources  |  Generate UUIDs in Typescript

Generating a UUID in TypeScript can be done using various methods. One of the most popular and reliable methods is using a third-party library like uuid. Here is how you can generate a UUID in TypeScript using the uuid library:

Using the uuid Library

  1. Install the uuid Library:

    You can install the uuid library along with its TypeScript types using npm:

    npm install uuid
    npm install @@types/uuid
    
  2. Generate UUID (v4) in TypeScript:

    Here is an example of how to generate a UUID using the uuid library:

    import { v4 as uuidv4 } from 'uuid';
    
    // Generate a new UUID (v4)
    const newUUID = uuidv4();
    
    // Output the generated UUID
    console.log('Generated UUID:', newUUID);
    

Explanation

  • import { v4 as uuidv4 } from 'uuid';: This line imports the v4 function from the uuid library and renames it to uuidv4 for clarity.
  • uuidv4(): This function generates a random UUID (UUIDv4).

Running the Code

  1. Save the Code: Save the TypeScript code in a file, for example, generateUUID.ts.

  2. Compile the Code: Use the TypeScript compiler to compile the TypeScript file:

    tsc generateUUID.ts
    
  3. Run the Compiled Code: Run the compiled JavaScript file using Node.js:

    node generateUUID.js
    

Output Example

When you run the compiled code, the output will be similar to:

Generated UUID: 123e4567-e89b-12d3-a456-426614174000

Each time you run the program, a different UUID will be generated.

Using a Custom Function (Without External Libraries)

If you prefer not to use external libraries, you can generate a UUID using a custom function. Here is an example:

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

// Generate a new UUID
const newUUID = generateUUIDv4();

// Output the generated UUID
console.log('Generated UUID:', newUUID);

Explanation

  • Math.random() * 16: Generates a random number between 0 and 15.
  • r & 0x3 | 0x8: Ensures the UUID version and variant bits are set correctly.
  • toString(16): Converts the number to a hexadecimal string.

Running the Custom Function Code

  1. Save the Code: Save the TypeScript code in a file, for example, generateUUID.ts.

  2. Compile and Run the Code: Use the TypeScript compiler and Node.js to compile and run the code:

    tsc generateUUID.ts
    node generateUUID.js
    

Summary

Here are two methods to generate UUIDs in TypeScript:

  1. Using the uuid library:

    import { v4 as uuidv4 } from 'uuid';
    
    const newUUID = uuidv4();
    console.log('Generated UUID:', newUUID);
    
  2. Using a custom function:

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

These methods provide flexible options for generating UUIDs in TypeScript, whether you prefer using a library or a custom implementation.