Null objects
By default, ValueObject returns a null object when constructed with null or undefined.
import { NullObject, StringValueObject } from '@haskou/value-objects';
const value = new StringValueObject(undefined as never);
NullObject.isNullObject(value); // true
value.valueOf(); // undefinedDisable automatic creation
Applications that prefer explicit failures can disable automatic NullObject creation globally:
import { ValueObject } from '@haskou/value-objects';
ValueObject.disableNullObjectCreation();
new StringValueObject(undefined as never);
// throws NullObjectCreationDisabledErrorRestore the default behavior with:
ValueObject.enableNullObjectCreation();This setting is process-wide. Configure it once during application bootstrap rather than toggling it around individual domain operations.
Method calls
Null objects expose fake methods from the target class. Calling those methods throws NullObjectError.
const value = new StringValueObject(undefined as never);
value.isEmpty(); // throws NullObjectErrorTime and coordinates
Day, Hour, Duration, CalendarDay, MonthOfYear, TimestampInterval, Latitude, Longitude and Coordinates follow the same rule as the rest of the package: nullish input returns a NullObject instead of throwing TypeError. Composites such as TimestampInterval and Coordinates return a NullObject when any of their parts is nullish.
const day = new Day(undefined as never);
NullObject.isNullObject(day); // true
day.valueOf(); // undefinedWhen to check
if (NullObject.isNullObject(value)) {
// Handle missing value explicitly.
}Use this when input can be absent and the calling code wants to preserve the value-object shape until a method is actually used. Use disableNullObjectCreation() instead when nullish construction should fail immediately.