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 set of APIs inside
effect
that allows to decode and encode data based on a schema.
Schema became part of
effect
core since version 3.10 (course update commit).If you are using an older version of
effect
, you need to install a separate@effect/schema
package.pnpm add @effect/schema
The main change is that all the modules previously exported from
@effect/schema
are now exported fromeffect
directly:import { Arbitrary, AST, SchemaAST, FastCheck, JSONSchema, ParseResult, Pretty, Schema } from "@effect/schema" } from "effect"
The link to Effect playgrounds in this course are still using the old
@effect/schema
package.
Under the hood 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 Schema
:
Schema.Struct
: schema for an object with propertiesSchema.Number
: schema for anumber
Schema.String
: schema for astring
import { Schema } from "effect";
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?