Effect CommunityEC
Effect Community2y ago
4 replies
BinaryArtifex

Schema Classes with Equal and Hash in TypeScript

do schema classes also come baked in with Equal and Hash? im probably butchering the intent of schema classes here but can't seem to find a straight answer anywhere. essentially im just trying to create an abstract base type to prevent it ever being instantiated, but i also want to set some base methods/properties to make life easier with everything that extends the Entity class. i thought of using data.class but prefer schema.class for its baked in parsing

import * as S from "@effect/schema/Schema";
import { Equal, Hash } from "effect";
import { uuidv7 } from "uuidv7";

export abstract class Entity
  extends S.Class<Entity>("@core/domain/Entity")({
    id: S.UUID.pipe(
      S.propertySignature,
      S.withConstructorDefault(() => S.UUID.make(uuidv7())),
    ),
  })
  implements Equal.Equal
{
  [Hash.symbol](): number {
    return Hash.hash(this.id);
  }

  [Equal.symbol](that: unknown): boolean {
    if (that instanceof Entity) {
      return (
        Equal.equals(that.constructor.name, this.constructor.name) && Equal.equals(that.id, this.id)
      );
    }
    return false;
  }
}
Was this page helpful?