matchexpr
v0.0.3
Published
typesafe exhaustive pattern matching for discriminated unions and objects
Maintainers
Readme
import { match } from 'matchexpr'
type Data = { type: 'text', content: string } | { type: 'img', src: string }
type Result = { type: 'ok', data: Data } | { type: 'error', error: Error }
declare const result: Result
const html = match(result, 'type', {
error: () => <p>Oops! An error occurred</p>,
ok: ({ data }) =>
match(data, 'type', {
text: ({ content }) => <p>{content}</p>,
img: ({ src }) => <img src={src} />,
}),
})features
- very small bundle size (less than 200 bytes)
- concise syntax, no method chaining
usage
pnpm add matchexprimport { match } from 'matchexpr'
declare const color: 'red' | 'green' | 'blue'
match(color, {
red: () => 1,
green: () => 2,
blue: () => 3,
})
match(color, {
red: () => 1,
green: () => 2,
// ERROR: Property 'blue' is missing
})
match(color, {
red: () => 1,
green: () => 2,
blue: () => 3,
yellow: () => 4,
// ERROR: Property 'yellow' is not a valid case
})