github gvergnaud/ts-pattern v3.1.1

latest releases: v5.5.0, v5.4.0, v5.3.1...
3 years ago

Better inference of the output type

when not provided, ts-pattern tries to infer the Output type in Match<Input, Output> (the type of a match expression). Until now, the Output type was inferred from the return type of the first branch:

declare let n: number;
let res = match(n)
  .with(2, () => "two") // we return a string, the type of our match expression becomes `Match<number, string>`
  .with(__, () => null) // Type error! `null` isn't of type `string`
  .exhaustive();

This behavior was forcing us to specify the output type to match with match<number, string>(n).

With this release, ts-pattern is a bit smarter about it and automatically infers the Output as the union of the return types of all branches:

declare let n: number;
let res = match(n)
  .with(2, () => "two")
  .with(__, () => null)
  .exhaustive();

// res is inferred as `string | null`

Don't miss a new ts-pattern release

NewReleases is sending notifications on new releases.