Value Objects are immutable objects identified only by their values. They are used to describe or measure things (e.g., Name, Money, Address) and can be part of an Entity.
Core Concepts
- Immutability: While the library allows state changes via
set or change, it is highly recommended to create a new instance instead of modifying an existing one. - Validation: Use
isValidProps (static) for creation validation and the validation method for validating property changes during set or change operations. - History: If setters are enabled, the library tracks changes in a history log, allowing you to revert to previous states using
history().back(). - Creation: Use the static
create method, which returns a Result to ensure the object is valid before instantiation.
Key Methods
create(props): Returns IResult<ValueObject>.get(key): Retrieves a specific property.set(key).to(value): Updates a property (if not disabled).clone(): Creates a new instance with the same properties.toObject(): Transforms the value object into a plain object (useful for nested objects).createMany(items[]): A static method to instantiate multiple value objects at once.disableSetters: Pass { disableSetters: true } to the super constructor to enforce strict immutability.
import { Ok, Fail, Result, ValueObject } from "types-ddd";
export interface NameProps {
value: string;
}
export class Name extends ValueObject<NameProps>{
private constructor(props: NameProps) {
super(props, { disableSetters: true });
}
public static isValidProps({ value }: NameProps): boolean {
return value.length >= 3 && value.length <= 30;
}
public static create(value: string): Result<Name> {
if (!this.isValidProps({ value })) return Fail('Invalid length');
return Ok(new Name({ value }));
}
}
const result = Name.create('Jane');
if (result.isOk()) {
const name = result.value();
console.log(name.get('value'));
}