Skip to content

Instantly share code, notes, and snippets.

@genki
Last active January 21, 2024 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genki/3879a31f4e4688965eac2d8c8450e1a7 to your computer and use it in GitHub Desktop.
Save genki/3879a31f4e4688965eac2d8c8450e1a7 to your computer and use it in GitHub Desktop.
`outof`, the valibot utility method, that is a type guard for the `Output` type of the schema as like as the `is` does for `Input` type. In addition, you can use the parsed value if you specify `then` arg.
const outof = <T extends BaseSchema, R,
O = T extends BaseSchema<any, infer O> ? O : never,
>(schema:T, value:unknown, then?:(value:O) => R): value is O => {
const {issues, output} = safeParse(schema, value);
if (issues && issues.length > 0) return false;
if (then) then(output as O);
return true;
};
// USAGE example
const processThing = (thing:unknown) => {
outof(FooSchema, thing, foo => {
// using as foo
})) ||
outof(BarSchema, thing, bar => {
// using as bar
}));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment