This minor release adds 3 new features to the lib.
__.nullish
A new wildcard pattern, matching null | undefined
. Thanks a lot @m-rutter for implementing this and fixing some issues with pattern inference along the way! 🎉
import { match, __ } from 'ts-pattern';
const input = null;
const output = match<number | string | boolean | null | undefined>(input)
.with(__.string, () => 'it is a string!')
.with(__.number, () => 'it is a number!')
.with(__.boolean, () => 'it is a boolean!')
.with(__.nullish, () => 'it is either null or undefined!')
.with(null, () => 'it is null!')
.with(undefined, () => 'it is undefined!')
.run();
console.log(output);
// => 'it is either null or undefined!'
instanceOf
A new function creating a pattern, checking if a value is an instance of a particular class. This feature was requests in #24, it was possible implement it in userland using a when
pattern, but the types were a bit tricky so I thought it made sense to add first class support for this.
import { match, instanceOf } from 'ts-pattern';
class A {
a = 'a';
}
class B {
b = 'b';
}
const output = match<{ value: A | B }>({ value: new A() })
.with({ value: instanceOf(A) }, (a) => 'instance of A!')
.with({ value: instanceOf(B) }, (b) => 'instance of B!')
.exhaustive();
console.log(output);
// => 'instance of A!'
isMatching
A helper function to create a type guard function from a pattern. This can be really useful when making a runtime type assertion, for instance if you want to check that an API response matches what you are expecting.
import { isMatching, __ } from 'ts-pattern';
const isBlogPost = isMatching({
title: __.string,
content: __.string,
});
const res: unknown = await fetch(...)
if (isBlogPost(res)) {
// res: { title: string, content: string }
}