I want to create a TypeScript utility library for runtime type checking with a Result type pattern like Rust has. It should force consumers to handle both Success and Error cases, using mapped types to infer the error structure from the input schema.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Proposing a TypeScript runtime validation library with exhaustive Result pattern
I'm designing a TypeScript utility library that models runtime schema validation with a Rust-like Result type, enforcing consumers to handle both success and error cases through an exhaustive match function. The library will define recursive ValidationError mapped types inferred from the input schema, base validators (string, number, object, etc.), and a validate function returning Result<T, ValidationError<T>>. This approach ensures type-safe validation and forces exhaustive handling of validation outcomes.
Below is a minimal pattern for a runtime type‐checking utility that returns a Rust‑like Result and forces exhaustive handling of success/error. It uses mapped types to derive an error structure from the input schema so that each field’s validation errors are reflected in the error type.
You can expand this into a full library (adding more validators, error codes, nested arrays/objects, etc.). The key idea is:
Schema objects describe how to validate a value.
Result is a discriminated union (Ok vs Err) with a match helper that forces consumers to handle both cases.
ValidationError is derived from the schema to produce a nested error type.
Result type & match function
ts
type Ok<T> = { _tag: "Ok"; value: T };
type Err<E> = { _tag: "Err"; error: E };
export type Result<T, E> = Ok<T> | Err<E>;
export const ok = <T, E = never>(value: T): Result<T, E> => ({ _tag: "Ok", value });
export const err = <E, T = never>(error: E): Result<T, E> => ({ _tag: "Err", error });
/** Forces consumer to handle both cases. */
export function matchResult<T, E, R>(
res: Result<T, E>,
cases: { ok: (val: T) => R; err: (error: E) => R }
): R {
return res._tag === "Ok" ? cases.ok(res.value) : cases.err(res.error);
}
Base schema types
We’ll define a minimal set of validators: string, number, and object. You can add more (boolean, array, enums, unions, etc.) following the same pattern.
ts
type Validator<T, E> = {
parse: (input: unknown) => Result<T, E>;
};
// Primitive validators
export const string = (message = "Expected string"): Validator<string, string[]> => ({
parse(input) {
return typeof input === "string"
? ok(input)
: err([message]);
}
});
export const number = (message = "Expected number"): Validator<number, string[]> => ({
parse(input) {
return typeof input === "number"
? ok(input)
: err([message]);
}
});
/** Recurse through an object schema, producing nested errors per key. */
type ObjectSchema = { [key: string]: Validator<any, any> };
/** Error type inferred from the schema.
* If a field’s validator returns E (like string[]), the object error maps that field to E,
* nested recursively if the field is another object validator.
*/
type ValidationError<S extends ObjectSchema> = {
[K in keyof S]?: S[K] extends Validator<infer U, infer E>
? U extends object
// if the value is an object validator, allow nested error shape
? E | ValidationError<any>
: E
: string[];
};
export function object<S extends ObjectSchema>(shape: S): Validator<
{ [K in keyof S]: ReturnType<S[K]["parse"]> extends Result<infer T, any> ? T : never },
ValidationError<S>
> {
return {
parse(input: unknown) {
if (typeof input !== "object" || input === null) {
return err({ _self: ["Expected object"] } as ValidationError<S>);
}
const obj = input as Record<string, unknown>;
const out: Record<string, unknown> = {};
const errors: Record<string, any> = {};
for (const key in shape) {
const result = shape[key].parse(obj[key]);
if (result._tag === "Ok") {
out[key] = result.value;
} else {
errors[key] = result.error;
}
}
// If no errors, return Ok; otherwise Err with structured error object
if (Object.keys(errors).length === 0) {
return ok(out as any);
} else {
return err(errors as ValidationError<S>);
}
}
};
}
Example Usage
ts
// Define a schema
const userSchema = object({
name: string("Name must be a string"),
age: number("Age must be a number"),
});
// Validate some input
const res = userSchema.parse({ name: "Alice", age: "not a number" });
// Force exhaustive handling:
matchResult(res, {
ok: (user) => {
// user is { name: string; age: number }
console.log("Valid user:", user);
},
err: (errors) => {
// errors is { name?: string[]; age?: string[] }
// Here, age should have an error
console.error("Validation failed:", errors);
}
});
If you try to ignore errors or only handle success, TypeScript will complain because matchResult requires both ok and err. The error structure is derived from the schema, so you can’t accidentally mistype the error fields—TypeScript will catch that.
Extending the library
Add more validators: boolean, literal, array, tuple, union, enum, etc.
Add richer error data (codes, paths, messages).
Provide helper combinators (optional, nullable, minLength, maxLength, etc.).
Add a map/chain to Result for functional chaining.
Supply a safeParse‐like helper returning both typed data and error shape.
This pattern ensures:
Runtime validation of unknown input against typed schemas.
Typed success outputs and structured, schema-derived error types.
Exhaustive handling of success/error via the matchResult helper.