This is the core concept behind Zod, Valibot, and io-ts: a schema object that both validates at runtime AND infers TypeScript types.
type TypeMap = {
string: string;
number: number;
boolean: boolean;
array: unknown[];
object: Record<string, unknown>;
};
// Schema maps field names to TypeMap keys:
const userSchema = { name: 'string', age: 'number', active: 'boolean' } as const;
// InferSchema<S> derives the validated type:
type InferSchema<S extends Record<string, keyof TypeMap>> = {
[K in keyof S]: TypeMap[S[K]];
};
type User = InferSchema<typeof userSchema>;
// → { name: string; age: number; active: boolean }createValidator(schema)Returns a validate(value) function that:
{ ok: true, data: T } if the value matches every key/type in the schema{ ok: false, errors: string[] } listing all violationsValidation rules:
"Missing key: \"fieldName\"""\"fieldName\" must be number, got string"null or non-object input → ["Expected an object"]Supported type strings: 'string', 'number', 'boolean', 'array', 'object'
Sample tests