How to generate GUID in Typescript with code examples
- Admin
- Mar 6, 2024
- Typescript
This tutorial explains how to generate UUID or GUID in TypeScript with code examples.
There are two types of IDs that represent the same type value in TypeScript.
How to Generate UUID in TypeScript with Examples
Below are the steps required to generate GUIDs in TypeScript applications:
First, install the typescript-guid
library using the npm command:
npm i typescript-guid --save
This adds the dependency to package.json.
Once the package is installed in a TypeScript project.
import { Guid } from "guid-typescript";
export class Employee {
id: Guid;
name: string;
salary: number;
}
How to Pass a GUID in TypeScript
GUIDs are used as a type similar to string. They can be declared as member variables in a class:
import { Guid } from "guid-typescript";
export class Employee {
id: Guid;
name: string;
salary: number;
}
They can also be passed as arguments to functions.
function getById(id: Guid) {}
And used as a return type in a function.
function convertStringToGuid(id: string): Guid {}
Is there a UUID type in TypeScript?
There is no built-in type defined for representing GUIDs in TypeScript. Usually, GUIDs or UUIDs are represented as strings. However, if you want to represent them as types, you can use a custom type after installing the typescript-guid
npm library:
import { Guid } from "guid-typescript";
export class Employee {
id: Guid;
name: string;
salary: number;
}
What is the Default GUID Value?
A GUID is a 16-digit number generated using some algorithm. The default value is 0000-00000-00000-00000.
Is a UUID a String?
A UUID is a 125-bit value, which is represented as a 16-byte string. It is represented in string format separated by hyphens.