Skip to content

Schema 0.67 (Release)

When we work with schemas, it’s common to need to extract their types automatically. To make this easier, we’ve made some changes to the Schema interface. Now, you can easily access Type and Encoded directly from a schema without the need for Schema.Schema.Type and Schema.Schema.Encoded.

1
import { Schema } from "@effect/schema"
2
3
const PersonSchema = Schema.Struct({
4
name: Schema.String,
5
age: Schema.NumberFromString
6
})
7
8
type PersonType = typeof PersonSchema.Type
9
10
type PersonEncoded = typeof PersonSchema.Encoded

When dealing with data, creating values that match a specific schema is crucial. To simplify this process, we’ve introduced default constructors for various types of schemas: Structs, filters, and brands. Let’s dive into each of them with some examples to understand better how they work.

Example (Struct)

1
import { Schema } from "@effect/schema"
2
3
const MyStruct = Schema.Struct({
4
name: Schema.NonEmpty
5
})
6
7
MyStruct.make({ name: "a" }) // ok
8
MyStruct.make({ name: "" })
9
/*
10
throws
11
Error: { name: NonEmpty }
12
└─ ["name"]
13
└─ NonEmpty
14
└─ Predicate refinement failure
15
└─ Expected NonEmpty (a non empty string), actual ""
16
*/

Example (filter)

1
import { Schema } from "@effect/schema"
2
3
const MyNumber = Schema.Number.pipe(Schema.between(1, 10))
4
5
// const n: number
6
const n = MyNumber.make(5) // ok
7
MyNumber.make(20)
8
/*
9
throws
10
Error: a number between 1 and 10
11
└─ Predicate refinement failure
12
└─ Expected a number between 1 and 10, actual 20
13
*/

Example (brand)

1
import { Schema } from "@effect/schema"
2
3
const MyBrand = Schema.Number.pipe(
4
Schema.between(1, 10),
5
Schema.brand("MyNumber")
6
)
7
8
// const n: number & Brand<"MyNumber">
9
const n = MyBrand.make(5) // ok
10
MyBrand.make(20)
11
/*
12
throws
13
Error: a number between 1 and 10
14
└─ Predicate refinement failure
15
└─ Expected a number between 1 and 10, actual 20
16
*/

When utilizing our default constructors, it’s important to grasp the type of value they generate. In the MyBrand example, the return type of the constructor is number & Brand<"MyNumber">, indicating that the resulting value is a number with the added branding “MyNumber”.

This differs from the filter example where the return type is simply number. The branding offers additional insights about the type, facilitating the identification and manipulation of your data.

Note that default constructors are “unsafe” in the sense that if the input does not conform to the schema, the constructor throws an error containing a description of what is wrong. This is because the goal of default constructors is to provide a quick way to create compliant values (for example, for writing tests or configurations, or in any situation where it is assumed that the input passed to the constructors is valid and the opposite situation is exceptional).

When constructing objects, it’s common to want to assign default values to certain fields to simplify the creation of new instances. Our new Schema.withConstructorDefault combinator allows you to effortlessly manage the optionality of a field in your default constructor.

Example

1
import { Schema } from "@effect/schema"
2
3
const PersonSchema = Schema.Struct({
4
name: Schema.NonEmpty,
5
age: Schema.Number.pipe(
6
Schema.propertySignature,
7
Schema.withConstructorDefault(() => 0)
8
)
9
})
10
11
// The age field is optional and defaults to 0
12
console.log(PersonSchema.make({ name: "John" }))
13
// => { age: 0, name: 'John' }

Defaults are lazily evaluated, meaning that a new instance of the default is generated every time the constructor is called:

1
import { Schema } from "@effect/schema"
2
3
const PersonSchema = Schema.Struct({
4
name: Schema.NonEmpty,
5
age: Schema.Number.pipe(
6
Schema.propertySignature,
7
Schema.withConstructorDefault(() => 0)
8
),
9
timestamp: Schema.Number.pipe(
10
Schema.propertySignature,
11
Schema.withConstructorDefault(() => new Date().getTime())
12
)
13
})
14
15
console.log(PersonSchema.make({ name: "name1" }))
16
// => { age: 0, timestamp: 1714232909221, name: 'name1' }
17
console.log(PersonSchema.make({ name: "name2" }))
18
// => { age: 0, timestamp: 1714232909227, name: 'name2' }

Note how the timestamp field varies.

Defaults can also be applied using the Class API:

1
import { Schema } from "@effect/schema"
2
3
class Person extends Schema.Class<Person>("Person")({
4
name: Schema.NonEmpty,
5
age: Schema.Number.pipe(
6
Schema.propertySignature,
7
Schema.withConstructorDefault(() => 0)
8
),
9
timestamp: Schema.Number.pipe(
10
Schema.propertySignature,
11
Schema.withConstructorDefault(() => new Date().getTime())
12
)
13
}) {}
14
15
console.log(new Person({ name: "name1" }))
16
// => Person { age: 0, timestamp: 1714400867208, name: 'name1' }
17
console.log(new Person({ name: "name2" }))
18
// => Person { age: 0, timestamp: 1714400867215, name: 'name2' }

Our new Schema.withDecodingDefault combinator makes it easy to handle the optionality of a field during the decoding process.

1
import { Schema } from "@effect/schema"
2
3
const MySchema = Schema.Struct({
4
a: Schema.optional(Schema.String).pipe(Schema.withDecodingDefault(() => ""))
5
})
6
7
console.log(Schema.decodeUnknownSync(MySchema)({}))
8
// => { a: '' }
9
console.log(Schema.decodeUnknownSync(MySchema)({ a: undefined }))
10
// => { a: '' }
11
console.log(Schema.decodeUnknownSync(MySchema)({ a: "a" }))
12
// => { a: 'a' }

If you want to set default values both for the decoding phase and for the default constructor, you can use Schema.withDefaults:

1
import { Schema } from "@effect/schema"
2
3
const MySchema = Schema.Struct({
4
a: Schema.optional(Schema.String).pipe(
5
Schema.withDefaults({
6
decoding: () => "",
7
constructor: () => "-"
8
})
9
)
10
})
11
12
console.log(Schema.decodeUnknownSync(MySchema)({}))
13
// => { a: '' }
14
console.log(Schema.decodeUnknownSync(MySchema)({ a: undefined }))
15
// => { a: '' }
16
console.log(Schema.decodeUnknownSync(MySchema)({ a: "a" }))
17
// => { a: 'a' }
18
19
console.log(MySchema.make({})) // => { a: '-' }
20
console.log(MySchema.make({ a: "a" })) // => { a: 'a' }

We’ve refactored the system that handles user-defined custom messages to make it more intuitive.

Now, custom messages no longer have absolute precedence by default. Instead, it becomes an opt-in behavior by explicitly setting a new flag override with the value true. Let’s see an example:

Previous Approach

1
import { Schema } from "@effect/schema"
2
3
const MyString = Schema.String.pipe(
4
Schema.minLength(1),
5
Schema.maxLength(2)
6
).annotations({
7
// This message always takes precedence
8
// So, for any error, the same message will always be shown
9
message: () => "my custom message"
10
})
11
12
const decode = Schema.decodeUnknownEither(MyString)
13
14
console.log(decode(null)) // "my custom message"
15
console.log(decode("")) // "my custom message"
16
console.log(decode("abc")) // "my custom message"

As you can see, no matter where the decoding error is raised, the same error message will always be presented because in the previous version, the custom message by default overrides those generated by previous filters.

Now, let’s see how the same schema works with the new system.

Current Approach

1
import { Schema } from "@effect/schema"
2
3
const MyString = Schema.String.pipe(
4
Schema.minLength(1),
5
Schema.maxLength(2)
6
).annotations({
7
// This message is shown only if the maxLength filter fails
8
message: () => "my custom message"
9
})
10
11
const decode = Schema.decodeUnknownEither(MyString)
12
13
console.log(decode(null)) // "Expected a string, actual null"
14
console.log(decode("")) // `Expected a string at least 1 character(s) long, actual ""`
15
console.log(decode("abc")) // "my custom message"

To restore the old behavior (for example, to address the scenario where a user wants to define a single cumulative custom message describing the properties that a valid value must have and does not want to see default messages), you need to set the override flag to true:

1
import { Schema } from "@effect/schema"
2
3
const MyString = Schema.String.pipe(
4
Schema.minLength(1),
5
Schema.maxLength(2)
6
).annotations({
7
// By setting the `override` flag to `true`
8
// this message will always be shown for any error
9
message: () => ({ message: "my custom message", override: true })
10
})
11
12
const decode = Schema.decodeUnknownEither(MyString)
13
14
console.log(decode(null)) // "my custom message"
15
console.log(decode("")) // "my custom message"
16
console.log(decode("abc")) // "my custom message"

We’ve introduced a new API interface to the filter API. This allows you to access the refined schema using the exposed from field:

1
import { Schema } from "@effect/schema"
2
3
const MyFilter = Schema.Struct({
4
a: Schema.String
5
}).pipe(Schema.filter(() => /* some filter... */ true))
6
7
// const aField: typeof Schema.String
8
const aField = MyFilter.from.fields.a

The signature of the filter function has been simplified and streamlined to be more ergonomic when setting a default message. In the new signature of filter, the type of the predicate passed as an argument is as follows:

1
predicate: (a: A, options: ParseOptions, self: AST.Refinement) =>
2
undefined | boolean | string | ParseResult.ParseIssue

with the following semantics:

  • true means the filter is successful.
  • false or undefined means the filter fails and no default message is set.
  • string means the filter fails and the returned string is used as the default message.
  • ParseIssue means the filter fails and the returned ParseIssue is used as an error.

Example

1
import { Schema } from "@effect/schema"
2
3
const Positive = Schema.Number.pipe(
4
Schema.filter((n) => (n > 0 ? undefined : "must be positive"))
5
)
6
7
Schema.decodeUnknownSync(Positive)(-1)
8
/*
9
throws
10
Error: { number | filter }
11
└─ Predicate refinement failure
12
└─ must be positive
13
*/

The JSON Schema compiler has been refactored to be more user-friendly. Now, the make API attempts to produce the optimal JSON Schema for the input part of the decoding phase. This means that starting from the most nested schema, it traverses the chain, including each refinement, and stops at the first transformation found.

Let’s see an example:

1
import { JSONSchema, Schema } from "@effect/schema"
2
3
const MySchema = Schema.Struct({
4
foo: Schema.String.pipe(Schema.minLength(2)),
5
bar: Schema.optional(Schema.NumberFromString, {
6
default: () => 0
7
})
8
})
9
10
console.log(JSON.stringify(JSONSchema.make(MySchema), null, 2))

Now, let’s compare the JSON Schemas produced in both the previous and new versions.

Before

1
{
2
"$schema": "http://json-schema.org/draft-07/schema#",
3
"type": "object",
4
"required": ["bar", "foo"],
5
"properties": {
6
"bar": {
7
"type": "number",
8
"description": "a number",
9
"title": "number"
10
},
11
"foo": {
12
"type": "string",
13
"description": "a string at least 2 character(s) long",
14
"title": "string",
15
"minLength": 2
16
}
17
},
18
"additionalProperties": false,
19
"title": "Struct (Type side)"
20
}

As you can see, the JSON Schema produced has:

  • a required foo field, correctly modeled with a constraint ("minLength": 2)
  • a required numeric bar field

This happens because in the previous version, the JSONSchema.make API by default produces a JSON Schema for the Type part of the schema. That is:

1
type Type = Schema.Schema.Type<typeof MySchema>
2
/*
3
type Type = {
4
readonly foo: string;
5
readonly bar: number;
6
}
7
*/

However, typically, we are interested in generating a JSON Schema for the input part of the decoding process, i.e., in this case for:

1
type Encoded = Schema.Schema.Encoded<typeof MySchema>
2
/*
3
type Encoded = {
4
readonly foo: string;
5
readonly bar?: string | undefined;
6
}
7
*/

At first glance, a possible solution might be to generate the JSON Schema of Schema.encodedSchema(schema):

1
console.log(
2
JSON.stringify(JSONSchema.make(Schema.encodedSchema(MySchema)), null, 2)
3
)

But here’s what the result would be:

1
{
2
"$schema": "http://json-schema.org/draft-07/schema#",
3
"type": "object",
4
"required": ["foo"],
5
"properties": {
6
"foo": {
7
"type": "string",
8
"description": "a string",
9
"title": "string"
10
},
11
"bar": {
12
"type": "string",
13
"description": "a string",
14
"title": "string"
15
}
16
},
17
"additionalProperties": false
18
}

As you can see, we lost the "minLength": 2 constraint, which is the useful part of precisely defining our schemas using refinements.

After

Now, let’s see what JSONSchema.make API produces by default for the same schema:

1
{
2
"$schema": "http://json-schema.org/draft-07/schema#",
3
"type": "object",
4
"required": ["foo"],
5
"properties": {
6
"foo": {
7
"type": "string",
8
"description": "a string at least 2 character(s) long",
9
"title": "string",
10
"minLength": 2
11
},
12
"bar": {
13
"type": "string",
14
"description": "a string",
15
"title": "string"
16
}
17
},
18
"additionalProperties": false,
19
"title": "Struct (Encoded side)"
20
}

As you can verify, the refinement has been preserved.

For all the details, head over to our changelog.