first commit
This commit is contained in:
@@ -0,0 +1,65 @@
|
||||
# LiteralSchema
|
||||
|
||||
<!-- begin:auto-docs -->
|
||||
_(no submodules)_
|
||||
<!-- end:auto-docs -->
|
||||
## 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 | undefined` as literal types
|
||||
- Returns `VALIDATION.LITERAL.MISMATCH` on failure
|
||||
|
||||
## Usage: Basic Example
|
||||
|
||||
```typescript
|
||||
import { literal } from "@suaveplan/validation";
|
||||
|
||||
const ok = literal("ok");
|
||||
ok.parse("ok"); // "ok"
|
||||
ok.parse("error"); // throws ValidationError
|
||||
```
|
||||
|
||||
## Usage: Advanced Example
|
||||
|
||||
```typescript
|
||||
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.stringify` is used in error messages to safely represent all primitive types including `undefined` (shown as `undefined` string) and `null`.
|
||||
- Literal schemas are particularly efficient: the `_parse` body 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
|
||||
|
||||
```ts
|
||||
import z from "@suaveplan/validation";
|
||||
const ready = z.literal("ready");
|
||||
ready.parse("ready"); // "ready"
|
||||
```
|
||||
Reference in New Issue
Block a user