What You'll Learn
You'll learn how to use TypeScript's type system to prevent invalid date ranges at compile time by creating a validated DateRange type with smart constructors.
The Temporal Logic Problem
Imagine a calendar booking system where users can reserve time slots. If you naively model a date range like this:
type DateRange = {
startDate: Date;
endDate: Date;
};
You've created an impossible state: nothing stops someone from creating a range where startDate comes after endDate. That's logically invalid, but TypeScript won't complain.
// Compiles fine, but is nonsensical
const broken: DateRange = {
startDate: new Date('2024-12-31'),
endDate: new Date('2024-01-01')
};
The problem is that the type allows any combination of dates, leaving temporal validity to runtime checks.
Smart Constructors: Validation at Creation
The solution is a smart constructor pattern: make the type impossible to construct directly, and force all creation through a validation function.
// Opaque type - can't be constructed directly
type DateRange = {
readonly startDate: Date;
readonly endDate: Date;
readonly _brand: 'ValidDateRange'; // Brand for nominal typing
};
function createDateRange(
start: Date,
end: Date
): DateRange | { error: string } {
if (start > end) {
return { error: 'Start date must be before or equal to end date' };
}
return {
startDate: start,
endDate: end,
_brand: 'ValidDateRange'
};
}
Now you cannot create an invalid DateRange without TypeScript catching it:
const valid = createDateRange(
new Date('2024-01-01'),
new Date('2024-12-31')
);
const invalid = createDateRange(
new Date('2024-12-31'),
new Date('2024-01-01')
);
// TypeScript forces you to handle the error case
if ('error' in invalid) {
console.error(invalid.error);
} else {
// Only here do you have a valid DateRange
console.log(invalid.startDate);
}
The _brand property serves as a compile-time marker that distinguishes DateRange from plain objects with the same shape. Functions accepting DateRange can trust the temporal constraint has been validated.
Key Takeaway: By hiding direct construction and exposing only validated smart constructors, you can encode temporal constraints (like "start before end") directly into your type system, catching logical errors at compile time instead of discovering them in production.