Defining a schema

Goal: check that a value conforms to a predefined set of rules.

Instead of using if/else for every parameter we can define a structure that represents our desired data. That's what a schema is all about!

@effect/schema is a library in the effect ecosystem that allows to decode and encode data based on a schema.

Under the hood @effect/schema will check that the data conforms with every rule we defined, or report a detailed error of what went wrong.

In practice schema looks like a more powerful typescript interface.

Instead of defining a plain typescript interface:

interface Pokemon {
  id: number;
  order: number;
  name: string;
  height: number;
  weight: number;
}

We create a value that represents the same schema using @effect/schema:

  • Schema.Struct: schema for an object with properties
  • Schema.Number: schema for a number
  • Schema.String: schema for a string
import { Schema } from "@effect/schema";

const Pokemon = Schema.Struct({
  id: Schema.Number,
  order: Schema.Number,
  name: Schema.String,
  height: Schema.Number,
  weight: Schema.Number,
});

This looks strikingly similar to a normal interface, doesn't it?