npm ts-pattern 4.2.0
v4.2.0

latest releases: 5.5.0, 5.4.0, 5.3.1...
20 months ago

Features

Better inference for match and .with

match

When using match with an inline array, it will now infer its type as tuple automatically, even when not using as const. This means that exhaustiveness checking will also improve in this case:

function f(a: boolean, b: boolean) {
  // infered as `[boolean, boolean]`
  return (
    match([a, b])
      // we can pattern match on all cases
      .with([true, true], () => false)
      .with([false, true], () => true)
      .with([true, false], () => true)
      .with([false, false], () => false)
      // ✅ Failed in TS-pattern v4.1 but works in v4.2!
      .exhaustive()
  );
}

.with(...)

Thanks to the help of @Andarist, this release fixes a long-standing issue of .with.
Until now, patterns like P.array, P.union or P.when didn't have proper type inference when used in .with() directly. Here are a few behaviors that use to be incorrect and work now:

match<'a' | 'b'>('a')
  .with(P.union('this is wrong'), x => x)
  //            ~~~~~~~~~~~~~~~
  //            ❌ no longer type-check in v4.2
  .otherwise(x => x)

match<'a' | 'b'>('a')
  .with(P.array(123), x => x)
  //            ~~~
  //            ❌ no longer type-check in v4.2
  .otherwise(x => x)

match<'a' | 'b'>('a')
  .with(P.when((x) => true), x => x)
  //            👆
  //    used to be of type `unknown`, now `'a' | 'b'`
  .otherwise(x => x)

This also fixes the following issue: #140

Don't miss a new ts-pattern release

NewReleases is sending notifications on new releases.