Guid TypeScript
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
-
TypeError: Guid is not a constructor
cause Attempting to instantiate `Guid` directly using `new Guid()` after an incorrect `import Guid from 'guid-typescript;'` statement, or if `require` was used without destructuring.fixUse the static factory method `Guid.create()` to generate new GUIDs, and ensure `import { Guid } from 'guid-typescript';` or `const { Guid } = require('guid-typescript');`. -
TypeError: Guid.create is not a function
cause This usually occurs when `Guid` was imported incorrectly, possibly as a default import when it's a named export, or when attempting to call `create()` as a top-level function.fixEnsure `Guid` is imported as a named export (`import { Guid } from 'guid-typescript';`) and call the method as `Guid.create()`. -
Error: String does not represent a Guid
cause The string passed to `Guid.parse()` does not conform to the RFC4122 GUID (UUID) format.fixValidate the input string format using `Guid.isGuid(myString)` before calling `Guid.parse(myString)`. If the string is not valid, handle the error gracefully.
Warnings
- gotcha Directly comparing `Guid` objects with raw GUID strings (e.g., `myGuidObject == 'some-guid-string'`) will not work as expected due to type mismatch. Always use `myGuidObject.toString()` or `myGuidObject.raw()` for string comparisons, or `Guid.isGuid()` for validation.
- gotcha `Guid.parse(guidString)` will throw an `Error` if the input `guidString` is not a valid RFC4122 GUID format. It does not return `null` or `undefined` for invalid inputs.
- gotcha When migrating from older JavaScript GUID libraries that might return plain strings, ensure that type annotations are updated to `Guid` for consistency and type safety. Mixing `Guid` objects and `string` types for IDs can lead to unexpected behavior or TypeScript compilation errors.
Install
-
npm install guid-typescript -
yarn add guid-typescript -
pnpm add guid-typescript
Imports
- Guid class
import Guid from 'guid-typescript';
import { Guid } from 'guid-typescript'; - Guid class (CommonJS)
const Guid = require('guid-typescript');const { Guid } = require('guid-typescript'); - Static methods (e.g., create)
import { create } from 'guid-typescript'; create();import { Guid } from 'guid-typescript'; Guid.create();
Quickstart
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()}`);