Last active
January 21, 2024 21:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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