Skip to main content
Module

x/fun/mod.ts>schemable.schema

A collection of algebraic data types, lenses, and schemables based on a light weight higher kinded type implementation. Written for deno.
Latest
function schemable.schema
import { schemable } from "https://deno.land/x/fun@v2.0.0/mod.ts";
const { schema } = schemable;

A helper function to build a generic Schema that can be used with any Schemable.

Examples

Example 1

import { schema, TypeOf } from "./schemable.ts";
import { SchemableDecoder } from "./decoder.ts";
import { SchemableRefinement } from "./refinement.ts";
import { SchemableJsonBuilder, print } from "./json_schema.ts";
import { pipe } from "./fn.ts";

const mySchema = schema(s => pipe(
  s.struct({
    name: s.string(),
    age: s.number(),
  }),
  s.intersect(s.partial({
    interests: s.array(s.string()),
  }))
));

// Derive the type from the schema
type MySchema = TypeOf<typeof mySchema>;

const decode = mySchema(SchemableDecoder);
const refine = mySchema(SchemableRefinement);
const jsonSchema = mySchema(SchemableJsonBuilder);

const unknown1 = {
  name: "Batman",
  age: 45,
  interests: ["crime fighting", "cake", "bats"],
};
const unknown2 = {
  name: "Cthulhu",
  interests: ["madness"],
};

const decoded1 = decode(unknown1); // Success!
const decoded2 = decode(unknown2); // Failure with info

const refine1 = refine(unknown1); // true
const refine2 = refine(unknown2); // false

const jsonSchemaString = pipe(
  jsonSchema,
  print,
  json => JSON.stringify(json, null, 2),
); // Turns the jsonSchema into a prettified string

Type Parameters

A
optional
B = unknown
optional
C = unknown
optional
D = unknown
optional
E = unknown
optional
U extends Kind = Kind

Parameters

s: InferSchema<U, A, B, C, D, E>