2.3 KiB
LiteralSchema
(no submodules)
Purpose
LiteralSchema<T> validates that an input is strictly equal (===) to a specific primitive value. It supports strings, numbers, booleans, null, and undefined as literal values. This is the foundation for discriminated union patterns and exhaustive type guards.
Features
- Strict equality check (
===) against the literal value - Supports
string | number | boolean | null | undefinedas literal types - Returns
VALIDATION.LITERAL.MISMATCHon failure
Usage: Basic Example
import { literal } from "@suaveplan/validation";
const ok = literal("ok");
ok.parse("ok"); // "ok"
ok.parse("error"); // throws ValidationError
Usage: Advanced Example
import { union, literal, object, string } from "@suaveplan/validation";
// Discriminated union pattern
const SuccessResponse = object({ type: literal("success"), data: string() });
const ErrorResponse = object({ type: literal("error"), message: string() });
const Response = union([SuccessResponse, ErrorResponse]);
Response.parse({ type: "success", data: "ok" });
Response.parse({ type: "error", message: "not found" });
API Reference
literal<T extends string | number | boolean | null | undefined>(value: T): LiteralSchema<T>
Factory accepting the literal value to match.
_parse(input, ctx): T | INVALID
Uses === comparison. Returns VALIDATION.LITERAL.MISMATCH on failure with a message showing both expected and received values (via JSON.stringify).
Implementation Notes
JSON.stringifyis used in error messages to safely represent all primitive types includingundefined(shown asundefinedstring) andnull.- Literal schemas are particularly efficient: the
_parsebody is a single equality check with no iteration.
Parse Behaviour
z.literal("ready") accepts only the exact value "ready" and infers the literal type "ready" rather than the widened type string. Literal unions are written as z.union([z.literal("a"), z.literal("b")]) or the sugar z.enum(["a", "b"]) — the enum form is marginally faster because it compiles to a single Set membership check.
Further Usage: Basic Example
import z from "@suaveplan/validation";
const ready = z.literal("ready");
ready.parse("ready"); // "ready"