unacy / Parser
Type Alias: Parser<TOutput>
type Parser<TOutput> = (input) => TOutput;Defined in: packages/core/src/formatters.ts:98
Parser converts a plain string into a format-tagged value with validation.
Parsers are the gatekeeper that transforms raw (unbranded) string input into a WithFormat<T, F> branded value. They must validate the input fully before applying the brand — invalid inputs must throw, never produce tagged garbage.
Type Parameters
| Type Parameter | Description |
|---|---|
TOutput extends WithFormat<unknown, string> | Format-tagged type to produce (must extend WithFormat<T, F>) |
Parameters
| Parameter | Type | Description |
|---|---|---|
input | string | Plain string to parse and validate |
Returns
TOutput
Value tagged with the format brand
Throws
When the input string is invalid or does not match the expected format
Remarks
- Must validate input before tagging — never cast without checking
- Must throw
ParseError(or a subclass) on invalid input, not returnundefined - Use
createParserWithSchemafor Zod-backed validation
Example
type ISO8601Date = WithFormat<Date, 'ISO8601'>;
const parseISO: Parser<ISO8601Date> = (input) => {
const d = new Date(input);
if (isNaN(d.getTime())) throw new ParseError('ISO8601', input, 'Invalid date');
return d as ISO8601Date;
};Use When
Accepting user or external-system input that must be validated and branded before entering type-safe internal APIs.
Avoid When
The input is already validated and branded — passing it through a Parser again is redundant and incurs unnecessary validation overhead.
Pitfalls
NEVER return a silently cast invalid value (return invalid as TOutput) — doing so breaks the invariant that all WithFormat<T, F> values are valid, corrupting every downstream consumer that trusts the brand.
NEVER swallow parse errors with an empty catch block — callers rely on thrown ParseError instances to distinguish validation failures from other runtime errors.
See
- Formatter
- FormatterParser
- createParserWithSchema