unacy / createParserWithSchema
Function: createParserWithSchema()
function createParserWithSchema<F, T>(schema, format): Parser<WithFormat<T, F>>;Defined in: packages/core/src/utils/validation.ts:55
Create a Parser<WithFormat<T, F>> backed by a Zod-compatible schema.
Wraps a Zod (or Zod-compatible) schema's .parse() method to produce a typed Parser. On schema rejection, the Zod error message is re-thrown as a ParseError so callers always receive a consistent error type.
Type Parameters
| Type Parameter | Description |
|---|---|
F extends string | Format identifier string literal (e.g., 'HexColor') |
T | Base runtime type that the schema validates into |
Parameters
| Parameter | Type | Description |
|---|---|---|
schema | any | Any object with a .parse(input: string) method (Zod schema) |
format | F | Format identifier used in thrown ParseError instances |
Returns
Parser<WithFormat<T, F>>
Parser function that validates and tags values as WithFormat<T, F>
Throws
When schema.parse rejects the input
Example
import { z } from 'zod';
import { createParserWithSchema } from 'unacy';
type HexColor = WithFormat<string, 'HexColor'>;
const parseHex = createParserWithSchema<'HexColor', string>(
z.string().regex(/^#[0-9A-Fa-f]{6}$/),
'HexColor'
);
parseHex('#ff0000'); // OK → tagged as HexColor
parseHex('red'); // throws ParseErrorUse When
You already have a Zod schema for a format and want to produce a typed Parser with minimal boilerplate.
Avoid When
Your validation logic cannot be expressed as a Zod schema — write a custom Parser<T> instead, throwing ParseError on failure.
Pitfalls
NEVER pass a schema whose .parse() does not throw on invalid input — the returned parser relies on schema rejection to trigger ParseError.
See
- Parser
- ParseError