Type matching library for TypeScript.
This library provides constructions to cover your input with type checks and pattern-match on them.
npm install --save typematcher
TypeMatcher library contains 2 main components:
- type matchers - functions to check value matches a type
- matching dsl - constructs to map a type A to B using type matchers to refine
TypeMatcher is a type alias for a function returning
true if its argument type matches:
Some type matchers:
Matching DSL consists of few functions:
Default case handler:
Composing type matchers:
Sometimes is simpler to use
switch/case but unfortunately not as an expression.
For more examples - check links in documentation section.
Case handlers type variance
Avoid explicitly setting argument type in
caseWhen() handler function, let type inferred by compiler.
You may set more specific type, but check will bring you more general one and compiler will not fail.
This is caused by TypeScript Function Parameter Bivariance
UPD: Typescript v2.6 brings
--strictFunctionTypes compiler option and if it's on, for this code:
match8, caseWhenisNumber,"n is 10"
you will now get this error:
error TS2345: Argument of type '8' is not assignable to parameter of type '10'. match(8, caseWhen(isNumber, (n: 10) => "n is 10")) ~
caseDefault at the end
match will execute all cases as provided, so first matching will return,
New match DSL introduced in
email@example.com brought compile-time exhaustivity checking, so this code:
will fail at compile time with:
error TS2322: Type 'string' is not assignable to type '"ten" | "twenty"'. const x: "ten" | "twenty" = match(8 as any, ~
But you still have to handle default case when
any result type is expected (which is highly not recommended), otherwise it may fail with
No match error at runtime.
Perfection is Achieved Not When There Is Nothing More to Add, But When There Is Nothing Left to Take Away
Fork, Contribute, Push, Create pull request, Thanks.
Check latest sources on github: https://github.com/lostintime/node-typematcher.
Pattern matching for typescript blog post.
Funfix binding: https://github.com/lostintime/node-typematcher-funfix.