Define schemas that perform runtime checks. Infer the Typescript types from those schemas. Error messages and stack traces do not expose any Personally Identifiable Information (PII) or Protected Health Information (PHI). Does not crash TSC inference until objects are very large. Outputs readable human messages (out-of-the-box). This is not a library to validate forms on the frontend. Its main focus is to validate JSON payloads on the backend. Our goal is to reject faulty payloads promptly to minimize system load.
// @filename: src/index.ts
import { t, Infer } from "typegate";
const person = t.object(
t.property('firstname', t.string),
t.optionalProperty('age', t.number),
t.property('children', t.array(t.object(
t.property('name', t.string),
t.optionalProperty('favoriteActivity', t.union(t.literal('Basketball'), t.literal('Drawing')))
)))
);
type Person = Infer<typeof person>;
const someData: unknown = {
firstname: 'Someone',
children: [
{name: '1st kid'},
{name: '2nd kid', favoriteActivity: 123}
],
};
const result = person.parse(someData);
if (!result.success) {
// The property at "<root>.children[1].favoriteActivity"
// was supposed to be one of "Basketball" | "Drawing" but it was a number.
console.log(result.error);
return;
}
const aPerson = result.value;
aPerson.agechildrenfirstname
Pros
-
No input data in the error AST to prevent PII/PHI leaks in logs.
-
Fails at first encountered error.
-
Out-of-the-box human-readable messages.
-
Minimalist (10% of most popular alternatives).
-
Faster at runtime than most popular alternatives.
-
Easier on TSC than most popular alternatives.
-
No dependencies.