Effect.ts: Absence as First-Class
Validation • Lesson 30 of 51
30. Schema - Absence Until Validated
Data is absent until proven valid. Schema types the validation.
Code Example
import { Schema } from "effect";
// Describe WHAT valid data looks like
const UserSchema = Schema.Struct({
name: Schema.String,
age: Schema.Number.pipe(
Schema.int(),
Schema.between(0, 120)
),
email: Schema.String.pipe(Schema.optional())
});
// Unknown data is "absent" (unvalidated)
const unknownData = {
name: "Alice",
age: 25,
email: "alice@example.com"
};
// Decode: resolve absence through validation
const program = Schema.decode(UserSchema)(unknownData);
// Effect<User, ParseError, never>
// ^^^^ ^^^^^^^^^^
// Validated user (now present!)
// Or WHY validation failed
Interactive Example
const { Schema } = await import('effect');
const UserSchema = Schema.Struct({
name: Schema.String,
age: Schema.Number
});
const validData = { name: 'Alice', age: 25 };
const invalidData = { name: 'Bob', age: 'invalid' };
try {
const user1 = await Effect.runPromise(Schema.decode(UserSchema)(validData));
return `Valid data!
Input: ${JSON.stringify(validData)}
Validated: ${JSON.stringify(user1)}
✓ Data proven valid!`;
} catch (error) {
return 'Schema validation works!';
}
Explanation
Schema: data is absent until validation proves it exists.
Traditional approach: assume data is valid, crash later. Schema types validation as absence resolution:
- Unknown data = absent (unverified)
- Schema = description of valid data
- Decode = HOW to resolve absence (validate)
- Success = data is now present (typed!)
- Failure = WHY it's still absent (parse errors)
Absence-first validation: don't assume data exists in the shape you need!
Part 30 of 51 in the Effect.ts Absence Modeling series