zod-value-object
v0.1.3
Published
TypeScript implementation of a base ValueObject based on the zod library
Downloads
37
Maintainers
Readme
zod-value-object
Fully typed value objects for TypeScript build on top of zod
Motivation
This library provides a small utility class that guarantees three things:
- ValueObjects are immutable
- ValueObjects are typesafe
- ValueObjects are value-equal (equal if their values are equal)
Installation
npm install zod-value-object # npm
yarn add zod-value-object # yarn
pnpm add zod-value-object # pnpm
Usage
import { ValueObject } from 'zod-value-object';
/* Primitives */
const schema = z.string().email();
class Email extends ValueObject('Email', schema) {}
const email = new Email('[email protected]');
console.log(email.value); // => "[email protected]"
/* Other Types */
const schema = z.object({ email: z.string() });
const schema = z.object({ email: Email }); // => Can use ValueObjects as schema
class Obj extends ValueObject('Obj', schema) {}
const obj = new Obj({ email: '[email protected]' });
const obj = new Obj({ email: email }); // => Can use ValueObjects as input
Immutability
const schema = z.string().email();
class Email extends ValueObject('Email', schema) {}
const email = new Email('[email protected]');
email.value = '[email protected]'; // => throws Error, same on nested properties
Typesafety
const schema = z.string().email();
class Email extends ValueObject('Email', schema) {}
const email = new Email('[email protected]');
/* Wrong input */
const email = new Email(22); // => throws InvalidInputError
/* Use as parameter type */
const useEmail = (email: Email) => {
//
};
useEmail(email); // => works
useEmail('someEmail'); // => throws TypeScript error
class OtherString extends ValueObject('OtherString', schema) {}
const otherString = new OtherString('[email protected]');
useEmail(otherString); // => also throws TypeScript error
Equality
const schema = z.string().email();
class Email extends ValueObject('Email', schema) {}
const email = new Email('[email protected]');
const sameEmail = new Email('[email protected]');
const otherEmail = new Email('[email protected]');
console.log(email === sameEmail); // => true
console.log(email.equals(sameEmail)); // => true
console.log(email === otherEmail); // => false
console.log(email.equals(otherEmail)); // => false