Type-safe Entity ID with phantom types to prevent mixing IDs of different entity types.

The phantom type parameter T is used to make IDs type-incompatible across different entities, preventing common bugs like passing a UserId where an OrderId is expected.

type UserId = EntityId<'User'>;
type OrderId = EntityId<'Order'>;

const userId = EntityId.create<'User'>();
const orderId = EntityId.create<'Order'>();

function getUser(id: UserId) { }

getUser(userId); // ✓ OK
getUser(orderId); // ✗ Compile error: Type 'OrderId' is not assignable to type 'UserId'

Type Parameters

  • T extends string

    Phantom type representing the entity type (e.g., 'User', 'Order')

Hierarchy (View Summary)

Accessors

Methods

  • Creates a new EntityId with a random UUID.

    Type Parameters

    • T extends string

      The entity type

    Returns EntityId<T>

    A new EntityId instance

    const userId = EntityId.create<'User'>();
    console.log(userId.value); // "550e8400-e29b-41d4-a716-446655440000"
  • Creates an EntityId from an existing string value. Useful when reconstructing entities from persistence.

    Type Parameters

    • T extends string

      The entity type

    Parameters

    • value: string

      The string representation of the ID

    Returns EntityId<T>

    An EntityId instance

    const userId = EntityId.from<'User'>('550e8400-e29b-41d4-a716-446655440000');
    
  • Returns the components that determine equality for this Value Object. Two Value Objects are equal if all their equality components are equal.

    Returns unknown[]

    An array of values used for equality comparison

  • Compares this Value Object with another for equality. Value Objects are equal if they are of the same type and all equality components match.

    Parameters

    • other: ValueObject

      The other Value Object to compare with

    Returns boolean

    true if the Value Objects are equal, false otherwise