Schemas and validation in TypeScript
The purpose of this package is to ease input validation in TypeScript projects.
import * as Schema from "@bakerface/schema";
export type User = Schema.TypeOf<typeof User>;
export const User = Schema.shape({
id: Schema.string,
username: Schema.string,
age: Schema.number,
bio: Schema.optional(Schema.string),
interests: Schema.arrayOf(Schema.string),
permissions: Schema.recordOf(Schema.boolean),
role: Schema.oneOf([
Schema.constant("guest"),
Schema.constant("moderator"),
Schema.constant("admin"),
]),
});
export const parseUser = Schema.parser(User);
export const isUser = Schema.guard(User);
const user = {};
if (isUser(user)) {
console.log(user.permissions.canCreateArticle);
}
const john = parseUser("john", user);
console.log(john.interests.length);