github.com/blu-j/ts-matches

Being able to pattern match in typescript

Open this visualization on its own page →

Contributors

4

Lines of Code

731

From

2018-09-04

To

2021-02-15

About blu-j/ts-matches

ts-matches is a TypeScript library that brings pattern matching capabilities to the language, enabling developers to validate schemas, perform type-safe switches, and match against complex data structures while maintaining full TypeScript type inference. The library provides a fluent API with methods like `shape`, `arrayOf`, `literal`, and `guard` that allow you to define validators which both check data at runtime and automatically narrow TypeScript types appropriately.

The project addresses a key limitation of traditional JSON validators like ajv by coupling validation logic with type information. When you parse data using ts-matches, you get back either the correctly typed value or an error, and TypeScript understands the refined type without requiring separate type assertions. This makes it particularly useful at system boundaries like API endpoints where data shape is unknown, and the library supports advanced patterns including optional fields, default values, recursive types, and custom refinement functions.

ts-matches uses an either-type pattern to handle validation results and provides both unsafe casting (throwing on failure) and safe parsing (returning typed results). The library is designed to work as an expression-based system where pattern matches can return values, and it includes utilities for dictionary validation, tuple matching, regex patterns, and conditional matching through the `some` combinator for multiple alternatives.

Share this video