This is a great request. The user wants to create a TypeScript utility library for runtime type checking with:
- A Result type pattern (like Rust's Result<T, E>)
- Forcing consumers to handle both Success and Error cases
- Using mapped types to infer error structure from input schema
Let me design this comprehensively:
- Core Result type - Similar to Rust's Result<T, E>
- Schema validation - A way to define runtime schemas
- Error inference - Mapped types to infer error structures from validation failures
- Exhaustiveness checking - Force handling both cases
- Utilities - Common operations like map, flatMap, getOrElse, etc.
Here's what I'll create:
- A
Validator interface for defining schemas
- A
Result<T, E> discriminated union type
- Schema builders (string, number, object, array, etc.)
- Error types that track which fields failed
- Utility functions for working with Results
- Examples showing the pattern
Let me write comprehensive code with good documentation:
// core/result.ts - Result type definition
// validators/ - Schema and validation logic
// utils/ - Helper utilities
// examples/ - Usage examples
I'll make sure to:
- Use discriminated unions for Result type
- Create mapped types for error inference
- Make error handling exhaustive
- Provide utility functions that are similar to Rust's Result methods
- Include examples showing how to use it
TypeScript Runtime Type Checking with Result Pattern
I'll create a comprehensive utility library with runtime type checking and a Rust-like Result pattern.
Core Result Type
// src/core/result.ts
/**
* Discriminated Union Result type
* Forces consumers to handle both Success and Error cases
*/
export type Result<T, E> = Success<T, E> | Failure<T, E>;
export interface Success<T, E> {
readonly tag: 'success';
readonly value: T;
}
export interface Failure<T, E> {
readonly tag: 'failure';
readonly error: E;
}
// Constructor functions
export const success = <T, E = never>(value: T): Result<T, E> => ({
tag: 'success',
value,
});
export const failure = <T = never, E = unknown>(error: E): Result<T, E> => ({
tag: 'failure',
error,
});
// Type guards
export const isSuccess = <T, E>(result: Result<T, E>): result is Success<T, E> =>
result.tag === 'success';
export const isFailure = <T, E>(result: Result<T, E>): result is Failure<T, E> =>
result.tag === 'failure';
// Core utility methods
export class ResultUtils {
/**
* Map over success value, leaving error unchanged
*/
static map<T, E, U>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {
return isSuccess(result) ? success(fn(result.value)) : result;
}
/**
* FlatMap (monadic bind) for chaining operations
*/
static flatMap<T, E, U>(
result: Result<T, E>,
fn: (value: T) => Result<U, E>
): Result<U, E> {
return isSuccess(result) ? fn(result.value) : result;
}
/**
* Map over error, leaving success unchanged
*/
static mapError<T, E, E2>(
result: Result<T, E>,
fn: (error: E) => E2
): Result<T, E2> {
return isFailure(result) ? failure(fn(result.error)) : result;
}
/**
* Recover from error with a fallback value
*/
static recover<T, E>(
result: Result<T, E>,
fn: (error: E) => T
): T {
return isSuccess(result) ? result.value : fn(result.error);
}
/**
* Exhaustive pattern matching
*/
static match<T, E, R>(
result: Result<T, E>,
handlers: {
onSuccess: (value: T) => R;
onFailure: (error: E) => R;
}
): R {
return isSuccess(result)
? handlers.onSuccess(result.value)
: handlers.onFailure(result.error);
}
/**
* Get value or throw error
*/
static unwrap<T, E>(result: Result<T, E>): T {
if (isSuccess(result)) return result.value;
throw new Error(
`Called unwrap on a failure: ${JSON.stringify(result.error)}`
);
}
/**
* Get value or return default
*/
static getOrElse<T, E>(result: Result<T, E>, defaultValue: T): T {
return isSuccess(result) ? result.value : defaultValue;
}
/**
* Combine multiple results
*/
static all<T, E>(results: Result<T, E>[]): Result<T[], E[]> {
const values: T[] = [];
const errors: E[] = [];
for (const result of results) {
if (isSuccess(result)) {
values.push(result.value);
} else {
errors.push(result.error);
}
}
return errors.length > 0 ? failure(errors) : success(values);
}
/**
* Return first success, or all failures
*/
static any<T, E>(results: Result<T, E>[]): Result<T, E[]> {
const errors: E[] = [];
for (const result of results) {
if (isSuccess(result)) {
return result;
}
errors.push(result.error);
}
return failure(errors);
}
}
Schema and Validation System
// src/schema/validator.ts
export type ValidationError = {
path: string;
message: string;
value: unknown;
};
export type ValidationResult<T> = {
success: boolean;
value?: T;
errors?: ValidationError[];
};
export interface Validator<T> {
validate(value: unknown): ValidationResult<T>;
/**
* Inferred error type - maps to field validation errors
*/
readonly errorType: unique symbol;
}
/**
* Base validator implementation
*/
abstract class BaseValidator<T> implements Validator<T> {
declare readonly errorType: unique symbol;
abstract validate(value: unknown): ValidationResult<T>;
/**
* Map validator output
*/
map<U>(fn: (value: T) => U): Validator<U> {
const self = this;
return new (class extends BaseValidator<U> {
validate(value: unknown): ValidationResult<U> {
const result = self.validate(value);
return result.success
? { success: true, value: fn(result.value!) }
: result;
}
})();
}
/**
* Chain validators
*/
flatMap<U>(fn: (value: T) => Validator<U>): Validator<U> {
const self = this;
return new (class extends BaseValidator<U> {
validate(value: unknown): ValidationResult<U> {
const result = self.validate(value);
if (!result.success) return result;
return fn(result.value!).validate(result.value);
}
})();
}
/**
* Refine validator with custom predicate
*/
refine(
predicate: (value: T) => boolean,
message: string
): Validator<T> {
const self = this;
return new (class extends BaseValidator<T> {
validate(value: unknown): ValidationResult<T> {
const result = self.validate(value);
if (!result.success) return result;
if (!predicate(result.value!)) {
return {
success: false,
errors: [
{
path: '$',
message,
value: result.value,
},
],
};
}
return result;
}
})();
}
}
// Primitive validators
export class StringValidator extends BaseValidator<string> {
constructor(
private minLength?: number,
private maxLength?: number,
private pattern?: RegExp
) {
super();
}
validate(value: unknown): ValidationResult<string> {
if (typeof value !== 'string') {
return {
success: false,
errors: [
{
path: '$',
message: `Expected string, got ${typeof value}`,
value,
},
],
};
}
const errors: ValidationError[] = [];
if (this.minLength !== undefined && value.length < this.minLength) {
errors.push({
path: '$',
message: `String length must be at least ${this.minLength}`,
value,
});
}
if (this.maxLength !== undefined && value.length > this.maxLength) {
errors.push({
path: '$',
message: `String length must be at most ${this.maxLength}`,
value,
});
}
if (this.pattern && !this.pattern.test(value)) {
errors.push({
path: '$',
message: `String does not match pattern ${this.pattern}`,
value,
});
}
return errors.length > 0
? { success: false, errors }
: { success: true, value };
}
}
export class NumberValidator extends BaseValidator<number> {
constructor(
private min?: number,
private max?: number,
private integer?: boolean
) {
super();
}
validate(value: unknown): ValidationResult<number> {
if (typeof value !== 'number' || isNaN(value)) {
return {
success: false,
errors: [
{
path: '$',
message: `Expected number, got ${typeof value}`,
value,
},
],
};
}
const errors: ValidationError[] = [];
if (this.integer && !Number.isInteger(value)) {
errors.push({
path: '$',
message: 'Expected integer',
value,
});
}
if (this.min !== undefined && value < this.min) {
errors.push({
path: '$',
message: `Number must be at least ${this.min}`,
value,
});
}
if (this.max !== undefined && value > this.max) {
errors.push({
path: '$',
message: `Number must be at most ${this.max}`,
value,
});
}
return errors.length > 0
? { success: false, errors }
: { success: true, value };
}
}
export class BooleanValidator extends BaseValidator<boolean> {
validate(value: unknown): ValidationResult<boolean> {
return typeof value === 'boolean'
? { success: true, value }
: {
success: false,
errors: [
{
path: '$',
message: `Expected boolean, got ${typeof value}`,
value,
},
],
};
}
}
export class ArrayValidator<T> extends BaseValidator<T[]> {
constructor(private elementValidator: Validator<T>) {
super();
}
validate(value: unknown): ValidationResult<T[]> {
if (!Array.isArray(value)) {
return {
success: false,
errors: [
{
path: '$',
message: `Expected array, got ${typeof value}`,
value,
},
],
};
}
const results: T[] = [];
const errors: ValidationError[] = [];
for (let i = 0; i < value.length; i++) {
const result = this.elementValidator.validate(value[i]);
if (result.success) {
results.push(result.value!);
} else {
errors.push(
...(result.errors?.map((e) => ({
...e,
path: `$[${i}]${e.path === '$' ? '' : '.' + e.path}`,
})) || [])
);
}
}
return errors.length > 0
? { success: false, errors }
: { success: true, value: results };
}
}
export class OptionalValidator<T> extends BaseValidator<T | undefined> {
constructor(private validator: Validator<T>) {
super();
}
validate(value: unknown): ValidationResult<T | undefined> {
if (value === null || value === undefined) {
return { success: true, value: undefined };
}
return this.validator.validate(value);
}
}
export class LiteralValidator<T extends string | number | boolean> extends BaseValidator<T> {
constructor(private literal: T) {
super();
}
validate(value: unknown): ValidationResult<T> {
return value === this.literal
? { success: true, value: value as T }
: {
success: false,
errors: [
{
path: '$',
message: `Expected literal value ${this.literal}`,
value,
},
],
};
}
}
export class UnionValidator<T> extends BaseValidator<T> {
constructor(private validators: Validator<T>[]) {
super();
}
validate(value: unknown): ValidationResult<T> {
const allErrors: ValidationError[] = [];
for (const validator of this.validators) {
const result = validator.validate(value);
if (result.success) {
return result;
}
allErrors.push(...(result.errors || []));
}
return {
success: false,
errors: allErrors,
};
}
}
Object Schema with Error Inference
// src/schema/object-schema.ts
import { Validator, ValidationResult, ValidationError, BaseValidator } from './validator';
/**
* Mapped type to infer error structure from object schema
* Each field gets mapped to its validation errors
*/
export type ObjectErrors<T extends Record<string, Validator<any>>> = {
[K in keyof T]?: ValidationError[];
};
export class ObjectValidator<T extends Record<string, Validator<any>>> extends BaseValidator<
{
[K in keyof T]: T[K] extends Validator<infer U> ? U : never;
}
> {
constructor(private schema: T) {
super();
}
validate(value: unknown): ValidationResult<
{
[K in keyof T]: T[K] extends Validator<infer U> ? U : never;
}
> {
if (typeof value !== 'object' || value === null) {
return {
success: false,
errors: [
{
path: '$',
message: `Expected object, got ${typeof value}`,
value,
},
],
};
}
const obj = value as Record<string, unknown>;
const result: Record<string, unknown> = {};
const errors: ValidationError[] = [];
for (const [key, validator] of Object.entries(this.schema)) {
const validationResult = (validator as Validator<any>).validate(obj[key]);
if (validationResult.success) {
result[key] = validationResult.value;
} else {
errors.push(
...(validationResult.errors?.map((e) => ({
...e,
path: `$.${key}${e.path === '$' ? '' : '.' + e.path}`,
})) || [])
);
}
}
return errors.length > 0
? { success: false, errors }
: { success: true, value: result as any };
}
}
/**
* Builder for creating strongly-typed object validators
*/
export class SchemaBuilder<T extends Record<string, any> = {}> {
constructor(private schema: Record<string, Validator<any>> = {}) {}
field<K extends string, V>(
key: K,
validator: Validator<V>
): SchemaBuilder<T & { [P in K]: V }> {
return new SchemaBuilder({
...this.schema,
[key]: validator,
});
}
build(): ObjectValidator<any> {
return new ObjectValidator(this.schema);
}
/**
* Returns a Result-based validator
*/
validate(value: unknown): Result<T, ObjectErrors<any>> {
const validator = this.build();
const result = validator.validate(value);
if (result.success) {
return success(result.value);
}
// Map validation errors to field-based structure
const fieldErrors: ObjectErrors<any> = {};
for (const error of result.errors || []) {
const fieldPath = error.path.split('.')[1];
if (fieldPath) {
if (!fieldErrors[fieldPath]) {
fieldErrors[fieldPath] = [];
}
fieldErrors[fieldPath]!.push(error);
}
}
return failure(fieldErrors);
}
}
Validator Builders - DSL
// src/schema/builders.ts
import {
StringValidator,
NumberValidator,
BooleanValidator,
ArrayValidator,
OptionalValidator,
LiteralValidator,
UnionValidator,
} from './validator';
import { SchemaBuilder } from './object-schema';
export const v = {
/**
* String validator with fluent API
*/
string: (
config?: {
min?: number;
max?: number;
pattern?: RegExp;
}
) => new StringValidator(config?.min, config?.max, config?.pattern),
/**
* Number validator with fluent API
*/
number: (
config?: {
min?: number;
max?: number;
integer?: boolean;
}
) => new NumberValidator(config?.min, config?.max, config?.integer),
/**
* Boolean validator
*/
boolean: () => new BooleanValidator(),
/**
* Array validator
*/
array: <T,>(elementValidator: Validator<T>) => new ArrayValidator(elementValidator),
/**
* Optional/nullable validator
*/
optional: <T,>(validator: Validator<T>) => new OptionalValidator(validator),
/**
* Literal value validator
*/
literal: <T extends string | number | boolean,>(value: T) => new LiteralValidator(value),
/**
* Union validator
*/
union: <T,>(validators: Validator<T>[]) => new UnionValidator(validators),
/**
* Object schema builder
*/
object: <T extends Record<string, any> = {}>() => new SchemaBuilder<T>(),
};
Comprehensive Example
// examples/user-validation.ts
import { Result, ResultUtils, isSuccess, isFailure } from '../src/core/result';
import { v } from '../src/schema/builders';
import { ObjectErrors } from '../src/schema/object-schema';
// Define user schema with type inference
const userSchema = v
.object<{
id: number;
email: string;
name: string;
age?: number;
tags: string[];
}>()
.field('id', v.number({ integer: true, min: 1 }))
.field('email', v.string({ pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/ }))
.field('name', v.string({ min: 1, max: 100 }))
.field('age', v.optional(v.number({ integer: true, min: 0, max: 150 })))
.field('tags', v.array(v.string({ min: 1 })));
type User = {
id: number;
email: string;
name: string;
age?: number;
tags: string[];
};
type UserError = ObjectErrors<any>;
/**
* Exhaustive pattern matching example
*/
function processUser(data: unknown): string {
const result = userSchema.validate(data);
return ResultUtils.match(result, {
onSuccess: (user: User) => {
return `User created: ${user.name} (${user.email})`;
},
onFailure: (errors: UserError) => {
const messages = Object.entries(errors)
.flatMap(([field, fieldErrors]) =>
fieldErrors?.map((e) => ` ${field}: ${e.message}`) || []
)
.join('\n');
return `Validation failed:\n${messages}`;
},
});
}
/**
* Type-safe chaining example
*/
function validateAndEnrich(data: unknown): Result<User & { normalized: boolean }, UserError> {
return ResultUtils.map(userSchema.validate(data), (user) => ({
...user,
normalized: true,
}));
}
/**
* Error recovery example
*/
function getUserOrDefault(data: unknown): User {
const defaultUser: User = {
id: 0,
email: 'unknown@example.com',
name: 'Unknown',
tags: [],
};
return ResultUtils.recover(userSchema.validate(data), () => defaultUser);
}
/**
* Batch validation example
*/
function validateUsers(dataArray: unknown[]): Result<User[], UserError[]> {
const results = dataArray.map((data) => userSchema.validate(data));
return ResultUtils.all(results);
}
// Usage examples
const testData1 = {
id: 1,
email: 'john@example.com',
name: 'John Doe',
age: 30,
tags: ['admin', 'developer'],
};
console.log('Example 1 - Pattern Matching:');
console.log(processUser(testData1));
console.log('\nExample 2 - Type-safe chaining:');
const enriched = validateAndEnrich(testData1);
if (isSuccess(enriched)) {
console.log('Enriched user:', enriched.value);
}
console.log('\nExample 3 - Invalid data:');
const testData2 = {
id: -1,
email: 'invalid-email',
name: '',
tags: ['valid'],
};
console.log(processUser(testData2));
console.log('\nExample 4 - Array validation:');
const results = validateUsers([testData1, testData2, { id: 3, email: 'jane@example.com' }]);
if (isFailure(results)) {
console.log('Batch validation failed with', results.error.length, 'errors');
}
Advanced: Custom Result with Async Support
// src/core/async-result.ts
import { Result, isSuccess, isFailure } from './result';
export type AsyncResult<T, E> = Promise<Result<T, E>>;
export class AsyncResultUtils {
/**
* Map async operation result
*/
static async map<T, E, U>(
resultPromise: AsyncResult<T, E>,
fn: (value: T) => U
): AsyncResult<U, E> {
const result = await resultPromise;
return isSuccess(result) ? { tag: 'success', value: fn(result.value) } : result;
}
/**
* FlatMap for async operations
*/
static async flatMap<T, E, U>(
resultPromise: AsyncResult<T, E>,
fn: (value: T) => AsyncResult<U, E>
): AsyncResult<U, E> {
const result = await resultPromise;
return isSuccess(result) ? fn(result.value) : result;
}
/**
* Combine multiple async results
*/
static async all<T, E>(resultPromises: AsyncResult<T, E>[]): AsyncResult<T[], E[]> {
const results = await Promise.all(resultPromises);
const values: T[] = [];
const errors: E[] = [];
for (const result of results) {
if (isSuccess(result)) {
values.push(result.value);
} else {
errors.push(result.error);
}
}
return errors.length > 0
? { tag: 'failure', error: errors }
: { tag: 'success', value: values };
}
}
// Usage example
async function fetchAndValidateUser(
userId: number
): AsyncResult<User, string> {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
const result = userSchema.validate(data);
return isSuccess(result)
? { tag: 'success', value: result.value }
: { tag: 'failure', error: 'Validation failed' };
} catch (error) {
return { tag: 'failure', error: String(error) };
}
}
API Reference Documentation
// src/index.ts
/**
* TypeScript Runtime Type Checking with Result Pattern
*
* @example
* ```typescript
* const userSchema = v
* .object<User>()
* .field('name', v.string({ min: 1 }))
* .field('email', v.string({ pattern: EMAIL_REGEX }));
*
* const result = userSchema.validate(data);
*
* ResultUtils.match(result, {
* onSuccess: (user) => console.log('Valid user:', user),
* onFailure: (errors) => console.error('Invalid:', errors),
* });
* ```
*/
export * from './core/result';
export * from './core/async-result';
export * from './schema/validator';
export * from './schema/object-schema';
export * from './schema/builders';
Key Features
✅ Exhaustive Pattern Matching - match() enforces handling both cases
✅ Type-Safe Error Inference - Mapped types track field-level errors
✅ Fluent Validator API - Chainable validators with map, flatMap, refine
✅ Discrimination - isSuccess/isFailure type guards
✅ Async Support - AsyncResult for Promise-based operations
✅ Zero Runtime Overhead - Pure TypeScript, minimal bundle size
✅ Rust-like Methods - unwrap, getOrElse, recover, all, any
This library provides compile-time type safety combined with runtime validation, forcing consumers to handle errors properly!