github gvergnaud/ts-pattern v5.3.1

one month ago

Pattern-matching on symbol keys

Symbols used to be ignored in object patterns. They are now taken into account:

const symbolA = Symbol('symbol-a');
const symbolB = Symbol('symbol-b');

const obj = { [symbolA]: { [symbolB]: 'foo' } };
    
if (isMatching({ [symbolA]: { [symbolB]: 'bar' } }, obj)) {
   //  👆 Used to return true, now returns false!
   
   //  Since TS-Pattern wasn't reading symbols, this pattern used to be equivalent
   //  to the `{}` pattern that matches any value except null and undefined.
}

.exhaustive now throws a custom error

People have expressed the need to differentiate runtime errors that .exhaustive() might throw when the input is of an unexpected type from other runtime errors that could have happened in the same match expression. It's now possible with err instanceof NonExhaustiveError:

import { match, P, NonExhaustiveError }  from 'ts-pattern';

const fn = (input: string | number) => {
  return match(input)
    .with(P.string, () => "string!")
    .with(P.number, () => "number!")
    .exhaustive()
}

try {
  fn(null as string) // 👈 💥 
} catch (e) {
  if (e instanceof NonExhaustiveError) {
    // The input was invalid
  } else {
    // something else happened
  }
}

What's Changed

  • build(deps-dev): bump braces from 3.0.2 to 3.0.3 in /examples/gif-fetcher by @dependabot in #262
  • feat: throw custom ExhaustiveError when no matched pattern by @adamhamlin in #270
  • Symbols as keys by @Ayc0 in #272

New Contributors

Full Changelog: v5.2.0...v5.3.1

Don't miss a new ts-pattern release

NewReleases is sending notifications on new releases.