Guid TypeScript

1.0.9 · maintenance · verified Sun Apr 19

Guid TypeScript is a lightweight JavaScript library focused on generating RFC4122-compliant GUIDs (also known as UUIDs) specifically for TypeScript environments. It is currently at version 1.0.9, suggesting a stable codebase with a focus on maintenance rather than rapid feature development. The library provides a `Guid` class that encapsulates GUID values, offering both static methods for creating new GUIDs (`create`, `createEmpty`, `raw`), parsing strings into `Guid` instances (`parse`), and validating potential GUID values (`isGuid`). Additionally, `Guid` instances include methods for comparison (`equals`), emptiness checks (`isEmpty`), and conversion to string or JSON formats (`toString`, `toJSON`). Its key differentiator lies in providing strong TypeScript typing, which allows developers to leverage type safety when working with GUIDs as objects, rather than managing them as raw strings. This approach helps prevent common errors associated with string manipulation and ensures consistency across an application's data models.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic GUID creation, checking for emptiness, comparing GUIDs, parsing a string into a Guid instance, and validating GUIDs within a TypeScript class context.

import { Guid } from "guid-typescript";

interface IUser {
    id: Guid;
    username: string;
}

class User implements IUser {
    public id: Guid;
    public username: string;

    constructor(username: string) {
        this.id = Guid.create(); // Generates a new unique GUID
        this.username = username;
        console.log(`New user created: ${this.username} with ID: ${this.id.toString()}`);
    }

    static isValidUserId(potentialId: any): boolean {
        // Checks if a given value is a valid Guid instance or string representation
        return Guid.isGuid(potentialId);
    }

    equals(otherUser: User): boolean {
        // Compares two Guid instances
        return this.id.equals(otherUser.id);
    }
}

// Example Usage
const user1 = new User("alice_ts");
const user2 = new User("bob_ts");

const emptyGuid = Guid.createEmpty(); // Creates an all-zero GUID
const rawGuidString = Guid.raw();    // Creates a new GUID as a string
const parsedGuid = Guid.parse("a1b2c3d4-e5f6-7890-1234-567890abcdef"); // Parses a GUID string

console.log(`\nUser 1 ID (raw string format): ${user1.id.raw()}`);
console.log(`Is emptyGuid really empty? ${emptyGuid.isEmpty()}`); // true
console.log(`Generated raw GUID string: ${rawGuidString}`);
console.log(`Does user1 ID equal user2 ID? ${user1.equals(user2)}`); // false
console.log(`Is "hello-world" a valid Guid string? ${User.isValidUserId("hello-world")}`); // false
console.log(`Is parsedGuid an actual Guid instance? ${User.isValidUserId(parsedGuid)}`); // true
console.log(`Parsed GUID value: ${parsedGuid.toString()}`);

view raw JSON →