Unexpected Key Messages

Avatar of Hemanta SundarayHemanta Sundaray

By default, Schema strips extra keys from the input without complaint. But when you enable strict mode with { onExcessProperty: "error" }, extra keys cause UnexpectedKey issues. You can customize the error message for this scenario with the messageUnexpectedKey annotation on the struct:

schema.ts
import { Schema } from "effect";
const Strict = Schema.Struct({
name: Schema.String,
}).annotate({ messageUnexpectedKey: "Unknown field. Only 'name' is allowed" });
const result = Schema.decodeUnknownExit(Strict)(
{ name: "Alice", extra: "oops" },
{ onExcessProperty: "error" },
);
console.log(String(result));

Output:

Terminal
Failure(Cause([Fail(SchemaError(Unknown field. Only 'name' is allowed
at ["extra"]))]))

Without the annotation, the error would say: Unexpected key with value "oops" at ["extra"].

Sign in to save progress

Stay in the loop

Get notified when new chapters are added and when this course is complete.