Guid Typescript

1.0.3 · active · verified Sun Apr 19

typescript-guid is a lightweight utility library for generating, parsing, and manipulating Globally Unique Identifiers (GUIDs), also commonly known as UUIDs, within TypeScript and JavaScript environments. The current stable version is 1.0.3. The library offers a comprehensive set of static methods for creating new GUIDs, including empty GUIDs, parsing GUID strings into `Guid` objects, and validating arbitrary values against the GUID format. `Guid` instances support comparisons (case-insensitive since v1.0.1), emptiness checks, and serialization to string or JSON formats. It is a direct evolution of the original `guid-typescript` project, distinguished by its strong emphasis on type safety and a TypeScript-first API design, ensuring seamless integration into modern TypeScript codebases. The project's release cadence is primarily driven by bug fixes and dependency updates, indicating a stable and mature codebase.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates creating new GUIDs, parsing existing ones, comparing `Guid` instances, and validating GUID strings. It showcases the primary API methods for common UUID operations.

import { Guid } from "typescript-guid";

// Example class demonstrating basic Guid usage
export class UserProfile {
    public readonly id: Guid;
    public name: string;

    constructor(name: string, existingId?: string) {
        this.id = existingId ? Guid.parse(existingId) : Guid.create();
        this.name = name;
    }

    public equals(otherProfile: UserProfile): boolean {
        return this.id.equals(otherProfile.id);
    }

    public toString(): string {
        return `User: ${this.name}, ID: ${this.id.toString()}`;
    }
}

// Usage example:
const user1 = new UserProfile('Alice');
const user2 = new UserProfile('Bob', user1.id.toString()); // Bob gets Alice's ID
const user3 = new UserProfile('Charlie');

console.log(user1.toString());
console.log(user2.toString());
console.log(user3.toString());
console.log(`Are user1 and user2 the same? ${user1.equals(user2)}`); // Should be true
console.log(`Are user1 and user3 the same? ${user1.equals(user3)}`); // Should be false

// Check if a string is a valid Guid
const potentialGuid = "b77d409a-10cd-4a47-8e94-b0cd0ab50aa1";
console.log(`'${potentialGuid}' is a Guid: ${Guid.isGuid(potentialGuid)}`);

view raw JSON →