Developer's Center
TypeScript

Generate a UUID in TypeScript

TypeScript, a superset of JavaScript, offers additional features and static typing to enhance JavaScript development. In this comprehensive guide, we will explore how to generate UUIDs in TypeScript using the uuid library.

How to Generate a UUID in TypeScript

Although TypeScript and JavaScript do not have built-in support for UUID generation, you can utilize third-party libraries to achieve this. The recommended library for generating UUIDs in TypeScript is uuid, which supports version 1, 3, 4, and 5 UUIDs.

Installing the uuid Package

To begin, you need to install the uuid library. If you have a project with a package.json file, run the following command to add it as a dependency:

% npm install uuid

Alternatively, if you prefer a global installation on your computer, use this command:

% npm install -g uuid

Generating UUIDs

Once the uuid library is installed, you can start using it in your TypeScript code.

Here's an example of generating a version 4 UUID:

import {v4 as uuidv4} from 'uuid';
 
let myuuid = uuidv4();
 
console.out('The UUID is: ' + myuuid);

Explanation

  • Line #1 imports the version 4 UUID function. There are also functions available for generating version 1, 3 and 5 UUIDs.
  • Line #3 generates the UUID and saves it in the variable, myuuid.

The output from line #5 will be something like:

The UUID is: 119D2163-F16A-47AF-9DF7-418D3AF1455A

Note: While there are TypeScript typings available for the uuid library, they are not strictly necessary for typical usage. If you wish to install the typings, you can use the following command:

If you would like to install the TypeScript typings for the uuid Javascript library, you can use this command:

% npm install -D @types/uuid

The uuid library offers additional functions, such as converting UUIDs to byte arrays and vice versa. For more information, refer to the uuid library's GitHub page.

Conclusion

Generating UUIDs in TypeScript is made easy with the uuid library. By following the step-by-step guide and code examples provided in this comprehensive guide, you can generate unique identifiers for your TypeScript projects.

Explore the capabilities of the uuid library and leverage TypeScript's features to enhance your development workflow. TypeScript's static typing and additional language constructs make it a powerful tool for building robust applications.