Rust inspired pattern matching for Zod schemas
npm install zod-matcherRust inspired pattern matching for Zod schemas
``bash`
yarn add zod-matcher
`bash`
npm install zod-matcher
` rust
let x = 1;
match x {
1 => println!("one"),
2 => println!("two"),
3 => println!("three"),
_ => println!("anything"),
}
`
Equivalent with zod-matcher
` typescript
declare const x : number
match(x)
.case(z.literal(1), () => console.log('one'))
.case(z.literal(2), () => console.log('two'))
.case(z.literal(3), () => console.log('three'))
.default(() => console.log('anything'))
.parse()
`
` typescript
const x = 'A' as 'A' | 'B'
// Error "Unhandled cases"
match(x)
.case(z.literal('A'), console.log)
.parse()
// Resolve by adding case
match(x)
.case(z.literal('A'), console.log)
.case(z.literal('B'), console.log)
.parse()
// Or by adding default
match(x)
.case(z.literal('A'), console.log)
.default(console.log)
.parse()
`
` typescript
const x = 'A' as 'A' | 'B' | 'C';
match(x)
.case(z.literal('A'), console.log)
.case(z.literal('B'), console.log)
.default(x => x) // <== Type of x is "C"
.parse();
`
` typescript
const x = 'A' as 'A' | 'B' | 'C';
// Type of result is "A1" | "B2" | "C3"
const result = match(x)
.case(z.literal('A'), x => ${x}1 as const)${x}2
.case(z.literal('B'), x => as const)${x}3
.case(z.literal('C'), x => as const)`
.parse();
` typescript
// Throws error if no match
const result = match(x)
.case(z.string(), console.log)
.parse()
// Returns result of union type
// | { success: true, data: x }
// | { success: false, error: MatcherError }
const result = match(x)
.case(z.string(), console.log)
.safeParse()
``