Skip to content

unacy / createParserWithSchema

Function: createParserWithSchema()

ts
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 ParameterDescription
F extends stringFormat identifier string literal (e.g., 'HexColor')
TBase runtime type that the schema validates into

Parameters

ParameterTypeDescription
schemaanyAny object with a .parse(input: string) method (Zod schema)
formatFFormat 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

typescript
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 ParseError

Use 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

Released under the MIT License.