Created
December 19, 2023 16:15
-
-
Save akoenig/8e4d5bdd204c5bd3e90fe5685ab56bdd to your computer and use it in GitHub Desktop.
Pattern Matching in TypeScript
This file contains hidden or 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
// | |
// This is a code example from the blog post: | |
// | |
// https://andrekoenig.de/articles/pattern-matching-in-typescript | |
// | |
import { P, match } from "ts-pattern"; | |
type ProductWasAddedToCartEvent = Readonly<{ | |
type: "ProductWasAddedToCart"; | |
payload: Readonly<{ | |
productId: string; | |
quantity: number; | |
}>; | |
}>; | |
type ProductWasRemovedFromCart = Readonly<{ | |
type: "ProductWasRemovedFromCart"; | |
payload: Readonly<{ | |
productId: string; | |
}>; | |
}>; | |
type CartEvent = ProductWasAddedToCartEvent | ProductWasRemovedFromCart; | |
const events: CartEvent[] = [ | |
{ | |
type: "ProductWasAddedToCart", | |
payload: { | |
productId: "1", | |
quantity: 2, | |
}, | |
}, | |
{ | |
type: "ProductWasRemovedFromCart", | |
payload: { | |
productId: "1", | |
}, | |
}, | |
{ | |
type: "ProductWasAddedToCart", | |
payload: { | |
productId: "3", | |
quantity: 300, | |
}, | |
}, | |
{ | |
type: "ProductWasAddedToCart", | |
payload: { | |
productId: "4", | |
quantity: 320, | |
}, | |
}, | |
]; | |
function ProductsWithHighQuantityWereAddedToCart(event: CartEvent) { | |
return match(event) | |
.with( | |
{ | |
type: "ProductWasAddedToCart", | |
payload: { quantity: P.number.gt(100) }, | |
}, | |
(event) => event, | |
) | |
.otherwise(() => undefined); | |
} | |
const result = events.filter(ProductsWithHighQuantityWereAddedToCart); | |
console.log(result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment