True Myth / standard-schema / parserFor
Function: parserFor()
parserFor<
S
>(schema
):ParserFor
<InferOutput
<S
>>
Create a synchronous parser for unknown data to use with any library that implements Standard Schema (Zod, Arktype, Valibot, etc.).
The resulting parser will accept unknown
data and emit a Result
, which will be Ok
if the schema successfully validates, or a Err
with the Issue
s generated by the schema for invalid data.
Examples
Creating a parser with Zod:
import { parserFor } from 'true-myth/standard-schema';
import * as z from 'zod';
interface Person {
name?: string | undefined;
age: number;
}
const parsePerson = parserFor(z.object({
name: z.string().optional(),
age: z.number().nonnegative(),
}));
Creating a parser with Arktype:
import { parserFor } from 'true-myth/standard-schema';
import { type } from 'arktype';
interface Person {
name?: string | undefined;
age: number;
}
const parsePerson = parserFor(type({
'name?': 'string',
age: 'number>=0',
}));
Other libraries work similarly!
Once you have a parser, you can simply call it with any value and then use the normal Result
APIs.
parsePerson({ name: "Old!", age: 112 }).match({
Ok: (person) => {
console.log(`${person.name ?? "someone"} is ${person.age} years old.`);
},
Err: (error) => {
console.error("Something is wrong!", ...error.issues);
}
});
Throws
The parser created by parserFor
will throw an InvalidAsyncSchema
error if the schema it was created from produces an async result, i.e., a Promise
. Standard Schema is currently unable to distinguish between synchronous and asynchronous parsers due to limitations in Zod.
If you need to handle schemas which may throw, use asyncParserFor
instead. It will safely lift all results into a Task
, which you can then safely interact with asynchronously as usual.
Type Parameters
S
S
extends StandardSchemaV1
<unknown
, unknown
>
Parameters
schema
S
Returns
ParserFor
<InferOutput
<S
>>