Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TS-Pattern v5 base branch #139

Merged
merged 88 commits into from Jun 13, 2023
Merged

TS-Pattern v5 base branch #139

merged 88 commits into from Jun 13, 2023

Conversation

gvergnaud
Copy link
Owner

@gvergnaud gvergnaud commented Jan 22, 2023

Breaking changes

.with is now evaluated eagerly

In the previous version of TS-Pattern, no code would execute until you called .exhaustive() or .otherwise(...). For example, in the following code block, nothing would be logged to the console or thrown:

// TS-Pattern v4
type Input = { type: 'ok'; value: number } | { type: 'error'; error: Error };

// We don't call `.exhaustive`, so handlers don't run.
function someFunction(input: Input) {
  match(input)
    .with({ type: 'ok' }, ({ value }) => {
      console.log(value);
    })
    .with({ type: 'error' }, ({ error }) => {
      throw error;
    });
}

someFunction({ type: 'ok', value: 42 }); // nothing happens

In TS-Pattern v5, however, the library will execute the matching handler as soon as it finds it:

// TS-Pattern v5
someFunction({ type: 'ok', value: 42 }); // logs "42" to the console!

Handlers are now evaluated eagerly instead of lazily. In practice, this shouldn't change anything as long as you always finish your pattern matching expressions by either .exhaustive or .otherwise.

Matching on Maps and Sets

Matching Set and Map instances using .with(new Set(...)) and .with(new Map(...)) is no longer supported. If you want to match specific sets and maps, you should now use the P.map(keyPattern, valuePattern) and P.set(valuePattern) patterns:

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


const someFunction = (value: Set<number> | Map<string, number>) =>
  match(value)
-   .with(new Set([P.number]), (set) => `a set of numbers`)
-   .with(new Map([['key', P.number]]), (map) => `map.get('key') is a number`)
+   .with(P.set(P.number), (set) => `a set of numbers`)
+   .with(P.map('key', P.number), (map) => `map.get('key') is a number`)
    .otherwise(() => null);
  • The subpattern we provide in P.set(subpattern) should match all values in the set.
  • The value subpattern we provide in P.map(keyPattern, subpattern) should only match the values matching keyPattern for the whole P.map(..) pattern to match the input.

New features

chainable methods

TS-Pattern v5's major addition is the ability to chain methods to narrow down the values matched by primitive patterns, like P.string or P.number.

Since a few examples is worth a thousand words, here are a few ways you can use chainable methods:

P.number methods

const example = (position: { x: number; y: number }) =>
  match(position)
    .with({ x: P.number.gte(100) }, (value) => '๐ŸŽฎ')
    .with({ x: P.number.between(0, 100) }, (value) => '๐ŸŽฎ')
    .with(
      {
        x: P.number.positive().int(),
        y: P.number.positive().int(),
      },
      (value) => '๐ŸŽฎ'
    )
    .otherwise(() => 'x or y is negative');

Here is the full list of number methods:

  • P.number.between(min, max): matches numbers between min and max.
  • P.number.lt(max): matches numbers smaller than max.
  • P.number.gt(min): matches numbers greater than min.
  • P.number.lte(max): matches numbers smaller than or equal to max.
  • P.number.gte(min): matches numbers greater than or equal to min.
  • P.number.int(): matches integers.
  • P.number.finite(): matches all numbers except Infinity and -Infinity
  • P.number.positive(): matches positive numbers.
  • P.number.negative(): matches negative numbers.

P.string methods

const example = (query: string) =>
  match(query)
    .with(P.string.startsWith('SELECT'), (query) => `selection`)
    .with(P.string.endsWith('FROM user'), (query) => `๐Ÿ‘ฏโ€โ™‚๏ธ`)
    .with(P.string.includes('*'), () => 'contains a star')
    // Methods can be chained:
    .with(P.string.startsWith('SET').includes('*'), (query) => `๐Ÿคฏ`)
    .exhaustive();

Here is the full list of string methods:

  • P.string.startsWith(str): matches strings that start with str.
  • P.string.endsWith(str): matches strings that end with str.
  • P.string.minLength(min): matches strings with at least min characters.
  • P.string.maxLength(max): matches strings with at most max characters.
  • P.string.includes(str): matches strings that contain str.
  • P.string.regex(RegExp): matches strings if they match this regular expression.

Global methods

Some methods are available for all primitive type patterns:

  • P.{..}.optional(): matches even if this property isn't present on the input object.
  • P.{..}.select(): injects the matched value into the handler function.
  • P.{..}.and(pattern): matches if the current pattern and the provided pattern match.
  • P.{..}.or(pattern): matches if either the current pattern or the provided pattern match.
const example = (value: unknown) =>
  match(value)
    .with(
      {
        username: P.string,
        displayName: P.string.optional(),
      },
      () => `{ username:string, displayName?: string }`
    )
    .with(
      {
        title: P.string,
        author: { username: P.string.select() },
      },
      (username) => `author.username is ${username}`
    )
    .with(
      P.instanceOf(Error).and({ source: P.string }),
      () => `Error & { source: string }`
    )
    .with(P.string.or(P.number), () => `string | number`)
    .otherwise(() => null);

Variadic tuple patterns

With TS-Pattern, you are now able to create array (or more accurately tuple) pattern with a variable number of elements:

const example = (value: unknown) =>
  match(value)
    .with(
      // non-empty list of strings
      [P.string, ...P.array(P.string)],
      (value) => `value: [string, ...string[]]`
    )
    .otherwise(() => null);

Array patterns that include a ...P.array are called variadic tuple patterns. You may only have a single ...P.array, but as many fixed-index patterns as you want:

const example = (value: unknown) =>
  match(value)
    .with(
      [P.string, P.string, P.string, ...P.array(P.string)],
      (value) => `value: [string, string, string, ...string[]]`
    )
    .with(
      [P.string, P.string, ...P.array(P.string)],
      (value) => `value: [string, string, ...string[]]`
    )
    .with([], (value) => `value: []`)
    .otherwise(() => null);

Fixed-index patterns can also be set after the ...P.array variadic, or on both sides!

const example = (value: unknown) =>
  match(value)
    .with(
      [...P.array(P.number), P.string, P.number],
      (value) => `value: [...number[], string, number]`
    )
    .with(
      [P.boolean, ...P.array(P.string), P.number, P.symbol],
      (value) => `value: [boolean, ...string[], number, symbol]`
    )
    .otherwise(() => null);

Lastly, argument of P.array is now optional, and will default to P._, which matches anything:

const example = (value: unknown) =>
  match(value)
    //                         ๐Ÿ‘‡
    .with([P.string, ...P.array()], (value) => `value: [string, ...unknown[]]`)
    .otherwise(() => null);

.returnType

In TS-Pattern v4, the only way to explicitly set the return type of your match expression is to set the two <Input, Output> type parameters of match:

// TS-Pattern v4
match<
  { isAdmin: boolean; plan: 'free' | 'paid' }, // input type
  number // return type
>({ isAdmin, plan })
  .with({ isAdmin: true }, () => 123)
  .with({ plan: 'free' }, () => 'Oops!');
//                              ~~~~~~ โŒ not a number.

the main drawback is that you need to set the input type explicitly too, even though TypeScript should be able to infer it.

In TS-Pattern v5, you can use the .returnType<Type>() method to only set the return type:

match({ isAdmin, plan })
  .returnType<number>() // ๐Ÿ‘ˆ new
  .with({ isAdmin: true }, () => 123)
  .with({ plan: 'free' }, () => 'Oops!');
//                              ~~~~~~ โŒ not a number.

@gvergnaud gvergnaud marked this pull request as ready for review June 9, 2023 14:55
@zoontek
Copy link
Contributor

zoontek commented Jun 9, 2023

@gvergnaud Instead of returnType<number>, wouldn't it be easier to swap match generics and set a default for the Input?

@gvergnaud
Copy link
Owner Author

gvergnaud commented Jun 9, 2023

@zoontek TS-Pattern needs an input type that's as accurate as possible for the pattern inference and features like select and exhaustive to work, so I don't think this is possible.

In addition, I find match<Output, Input> to be really awkward, since function types are read from left to right: Input => Output.

The real fix would be for typescript to support partial inference on type parameters so we could do match<infer, Output>(...). I think I remember reading an issue about that, but I have no idea if this is planned work.

[EDIT] found the issue I was thinking about: microsoft/TypeScript#26242

@gvergnaud
Copy link
Owner Author

gvergnaud commented Jun 9, 2023

After reading these meeting notes discussing @Andarist's proposal of an additional preferinfer keyword to opt into partial inference at the definition site, it doesn't look like a consensus has been reached yet.

My (probably naive) opinion is that partial inference should just be the default, and we would also need some kind of keyword to let typescript infer a parameter that comes before the one we want to set explicitly:

declare function compute<A, B, C>(a: A, b: B, c: C): [A, B, C]

compute<infer, 1 | 2 | 3>("a", 2, true): [string, 1 | 2 | 3, boolean]

Looks like a pretty good syntax to me, even though this could be considered a breaking change, since unspecified type parameters would start to type check. I'm also not sure how this should interact with default parameters. They should probably override the inferred type?

Anyway, all of this is kind of unrelated to this PR, even though this feature would remove the need for an additional .returnType<Output>() function

@Andarist
Copy link

Andarist commented Jun 9, 2023

My (probably naive) opinion is that partial inference should just be the default,

That's also the opinion of the TS team. The problem is that changing the behavior today turns out to be quite breaking for a lot of code in the wild.

As to partial inference and my preferinfer proposal. The current status is that "Investigate Type Argument Placeholders" is on the 5.2 milestone and might be closed by microsoft/TypeScript#26349 . As library authors... we are still waiting for some way to annotate our signatures as preferring the inference though.

@gvergnaud gvergnaud merged commit 803554d into main Jun 13, 2023
turtton pushed a commit to turtton/volglass that referenced this pull request Mar 3, 2024
[![Mend
Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| [ts-pattern](https://togithub.com/gvergnaud/ts-pattern) | [`^4.1.4` ->
`^5.0.0`](https://renovatebot.com/diffs/npm/ts-pattern/4.1.4/5.0.6) |
[![age](https://developer.mend.io/api/mc/badges/age/npm/ts-pattern/5.0.6?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![adoption](https://developer.mend.io/api/mc/badges/adoption/npm/ts-pattern/5.0.6?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![passing](https://developer.mend.io/api/mc/badges/compatibility/npm/ts-pattern/4.1.4/5.0.6?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/ts-pattern/4.1.4/5.0.6?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|

---

### Release Notes

<details>
<summary>gvergnaud/ts-pattern (ts-pattern)</summary>

###
[`v5.0.6`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v5.0.6)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v5.0.5...v5.0.6)

#### Close issue issues

- Exhaustive matching fix for reas
[gvergnaud/ts-pattern#206
- Fix incorrect JS docs
[gvergnaud/ts-pattern#196

#### What's Changed

- Update README.md by
[@&#8203;ndstephens](https://togithub.com/ndstephens) in
[gvergnaud/ts-pattern#161
- docs: add install instructions for bun and pnpm by
[@&#8203;colinhacks](https://togithub.com/colinhacks) in
[gvergnaud/ts-pattern#186
- build(deps-dev): bump postcss from 8.4.23 to 8.4.31 by
[@&#8203;dependabot](https://togithub.com/dependabot) in
[gvergnaud/ts-pattern#199
- build(deps-dev): bump
[@&#8203;babel/traverse](https://togithub.com/babel/traverse) from
7.21.5 to 7.23.2 by
[@&#8203;dependabot](https://togithub.com/dependabot) in
[gvergnaud/ts-pattern#200
- fix(readonly): exhaustive matching on readonly array by
[@&#8203;gvergnaud](https://togithub.com/gvergnaud) in
[gvergnaud/ts-pattern#207

#### New Contributors

- [@&#8203;ndstephens](https://togithub.com/ndstephens) made their first
contribution in
[gvergnaud/ts-pattern#161
- [@&#8203;colinhacks](https://togithub.com/colinhacks) made their first
contribution in
[gvergnaud/ts-pattern#186

**Full Changelog**:
gvergnaud/ts-pattern@v5.0.5...v5.0.6

###
[`v5.0.5`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v5.0.5)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v5.0.4...v5.0.5)

#### Bug fixes

The `P` module was mistakenly exposing some pattern methods that were
intended to be namespaced by type. This release fixes this problem.

If you happened to use on of those following methods, here is where to
find them now:

```diff
- P.between
+ P.number.between
```

```diff
- P.lt
+ P.number.lt
```

```diff
- P.gt
+ P.number.gt
```

```diff
- P.lte
+ P.number.lte
```

```diff
- P.gte
+ P.number.gte
```

```diff
- P.int
+ P.number.int
```

```diff
- P.finite
+ P.number.finite
```

```diff
- P.positive
+ P.number.positive
```

```diff
- P.negative
+ P.number.negative
```

```diff
- P.betweenBigInt
+ P.bigint.between
```

```diff
- P.ltBigInt
+ P.bigint.lt
```

```diff
- P.gtBigInt
+ P.bigint.gt
```

```diff
- P.lteBigInt
+ P.bigint.lte
```

```diff
- P.gteBigInt
+ P.bigint.gte
```

```diff
- P.positiveBigInt
+ P.bigint.positive
```

```diff
- P.negativeBigInt
+ P.bigint.negative
```

###
[`v5.0.4`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v5.0.4)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v5.0.3...v5.0.4)

#### What's Changed

- ๐Ÿ› fix: Accept branded primitive types as patterns by
[@&#8203;gvergnaud](https://togithub.com/gvergnaud) in
[gvergnaud/ts-pattern#180

**Full Changelog**:
gvergnaud/ts-pattern@v5.0.3...v5.0.4

###
[`v5.0.3`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v5.0.3)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v5.0.2...v5.0.3)

#### What's Changed

- ๐Ÿ› fix: Allow re-exporting patterns from ES Modules by
[@&#8203;gvergnaud](https://togithub.com/gvergnaud) in
[gvergnaud/ts-pattern#175

**Full Changelog**:
gvergnaud/ts-pattern@v5.0.2...v5.0.3

###
[`v5.0.2`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v5.0.2)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/7ccc1d3333e424391f0b8e0f1ec0055025448bda...v5.0.2)

#### What's Changed

- fix(P.infer): Fix inference of arrays containing tuples in
gvergnaud/ts-pattern@c52af6a
- refactoring: simplify selection types in
gvergnaud/ts-pattern@1b7a36b
- perf: runtime perf improvement in .with in
gvergnaud/ts-pattern@9b27384
- fix: use `Symbol.for` to make sure two concurrent versions of
ts-pattern are compatible with one-another in
gvergnaud/ts-pattern@d6d2e23
- docs: fix typo by
[@&#8203;juicyjusung](https://togithub.com/juicyjusung) in
[gvergnaud/ts-pattern#170

#### New Contributors

- [@&#8203;juicyjusung](https://togithub.com/juicyjusung) made their
first contribution in
[gvergnaud/ts-pattern#170

**Full Changelog**:
gvergnaud/ts-pattern@v5.0.0...v5.0.2

###
[`v5.0.1`](https://togithub.com/gvergnaud/ts-pattern/compare/v5.0.0...7ccc1d3333e424391f0b8e0f1ec0055025448bda)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v5.0.0...7ccc1d3333e424391f0b8e0f1ec0055025448bda)

###
[`v5.0.0`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v5.0.0):
โค๏ธ

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v4.3.0...v5.0.0)

### TS-Pattern v5 is finally out โค๏ธ

### Breaking changes

#### `.with` is now evaluated eagerly

In the previous version of TS-Pattern, no code would execute until you
called `.exhaustive()` or `.otherwise(...)`. For example, in the
following code block, nothing would be logged to the console or thrown:

```ts
// TS-Pattern v4
type Input = { type: 'ok'; value: number } | { type: 'error'; error: Error };

// We don't call `.exhaustive`, so handlers don't run.
function someFunction(input: Input) {
  match(input)
    .with({ type: 'ok' }, ({ value }) => {
      console.log(value);
    })
    .with({ type: 'error' }, ({ error }) => {
      throw error;
    });
}

someFunction({ type: 'ok', value: 42 }); // nothing happens
```

In **TS-Pattern v5**, however, the library will execute the matching
handler as soon as it finds it:

```ts
// TS-Pattern v5
someFunction({ type: 'ok', value: 42 }); // logs "42" to the console!
```

Handlers are now evaluated **eagerly** instead of lazily. In practice,
this shouldn't change anything as long as you always finish your pattern
matching expressions by either `.exhaustive` or `.otherwise`.

#### Matching on Maps and Sets

Matching `Set` and `Map` instances using `.with(new Set(...))` and
`.with(new Map(...))` is no longer supported. If you want to match
specific sets and maps, you should now use the `P.map(keyPattern,
valuePattern)` and `P.set(valuePattern)` patterns:

```diff
- import { match } from 'ts-pattern';
+ import { match, P } from 'ts-pattern';

const someFunction = (value: Set<number> | Map<string, number>) =>
  match(value)
-   .with(new Set([P.number]), (set) => `a set of numbers`)
-   .with(new Map([['key', P.number]]), (map) => `map.get('key') is a number`)
+   .with(P.set(P.number), (set) => `a set of numbers`)
+   .with(P.map('key', P.number), (map) => `map.get('key') is a number`)
    .otherwise(() => null);
```

- The subpattern we provide in `P.set(subpattern)` should match all
values in the set.
- The value subpattern we provide in `P.map(keyPattern, subpattern)`
should only match the values matching `keyPattern` for the whole
`P.map(..)` pattern to match the input.

### New features

#### chainable methods

TS-Pattern v5's major addition is the ability to chain methods to narrow
down the values matched by primitive patterns, like `P.string` or
`P.number`.

Since a few examples is worth a thousand words, here are a few ways you
can use chainable methods:

##### P.number methods

```ts
const example = (position: { x: number; y: number }) =>
  match(position)
    .with({ x: P.number.gte(100) }, (value) => '๐ŸŽฎ')
    .with({ x: P.number.between(0, 100) }, (value) => '๐ŸŽฎ')
    .with(
      {
        x: P.number.positive().int(),
        y: P.number.positive().int(),
      },
      (value) => '๐ŸŽฎ'
    )
    .otherwise(() => 'x or y is negative');
```

Here is the full list of number methods:

- `P.number.between(min, max)`: matches numbers between `min` and `max`.
-   `P.number.lt(max)`: matches numbers smaller than `max`.
-   `P.number.gt(min)`: matches numbers greater than `min`.
-   `P.number.lte(max)`: matches numbers smaller than or equal to `max`.
-   `P.number.gte(min)`: matches numbers greater than or equal to `min`.
-   `P.number.int()`: matches integers.
- `P.number.finite()`: matches all numbers except `Infinity` and
`-Infinity`
-   `P.number.positive()`: matches positive numbers.
-   `P.number.negative()`: matches negative numbers.

##### P.string methods

```ts
const example = (query: string) =>
  match(query)
    .with(P.string.startsWith('SELECT'), (query) => `selection`)
    .with(P.string.endsWith('FROM user'), (query) => `๐Ÿ‘ฏโ€โ™‚๏ธ`)
    .with(P.string.includes('*'), () => 'contains a star')
    // Methods can be chained:
    .with(P.string.startsWith('SET').includes('*'), (query) => `๐Ÿคฏ`)
    .exhaustive();
```

Here is the full list of string methods:

-   `P.string.startsWith(str)`: matches strings that start with `str`.
-   `P.string.endsWith(str)`: matches strings that end with `str`.
- `P.string.minLength(min)`: matches strings with at least `min`
characters.
- `P.string.maxLength(max)`: matches strings with at most `max`
characters.
-   `P.string.includes(str)`: matches strings that contain `str`.
- `P.string.regex(RegExp)`: matches strings if they match this regular
expression.

##### Global methods

Some methods are available for all primitive type patterns:

- `P.{..}.optional()`: matches even if this property isn't present on
the input object.
- `P.{..}.select()`: injects the matched value into the handler
function.
- `P.{..}.and(pattern)`: matches if the current pattern **and** the
provided pattern match.
- `P.{..}.or(pattern)`: matches if either the current pattern **or** the
provided pattern match.

```ts
const example = (value: unknown) =>
  match(value)
    .with(
      {
        username: P.string,
        displayName: P.string.optional(),
      },
      () => `{ username:string, displayName?: string }`
    )
    .with(
      {
        title: P.string,
        author: { username: P.string.select() },
      },
      (username) => `author.username is ${username}`
    )
    .with(
      P.instanceOf(Error).and({ source: P.string }),
      () => `Error & { source: string }`
    )
    .with(P.string.or(P.number), () => `string | number`)
    .otherwise(() => null);
```

#### Variadic tuple patterns

With TS-Pattern, you are now able to create array (or more accurately
tuple) pattern with a variable number of elements:

```ts
const example = (value: unknown) =>
  match(value)
    .with(
      // non-empty list of strings
      [P.string, ...P.array(P.string)],
      (value) => `value: [string, ...string[]]`
    )
    .otherwise(() => null);
```

Array patterns that include a `...P.array` are called **variadic tuple
patterns**. You may only have a single `...P.array`, but as many
fixed-index patterns as you want:

```ts
const example = (value: unknown) =>
  match(value)
    .with(
      [P.string, P.string, P.string, ...P.array(P.string)],
      (value) => `value: [string, string, string, ...string[]]`
    )
    .with(
      [P.string, P.string, ...P.array(P.string)],
      (value) => `value: [string, string, ...string[]]`
    )
    .with([], (value) => `value: []`)
    .otherwise(() => null);
```

Fixed-index patterns can also be set **after** the `...P.array`
variadic, or on both sides!

```ts
const example = (value: unknown) =>
  match(value)
    .with(
      [...P.array(P.number), P.string, P.number],
      (value) => `value: [...number[], string, number]`
    )
    .with(
      [P.boolean, ...P.array(P.string), P.number, P.symbol],
      (value) => `value: [boolean, ...string[], number, symbol]`
    )
    .otherwise(() => null);
```

Lastly, argument of `P.array` is now optional, and will default to
`P._`, which matches anything:

```ts
const example = (value: unknown) =>
  match(value)
    //                         ๐Ÿ‘‡
    .with([P.string, ...P.array()], (value) => `value: [string, ...unknown[]]`)
    .otherwise(() => null);
```

#### `.returnType`

In TS-Pattern v4, the only way to explicitly set the return type of your
`match` expression is to set the two `<Input, Output>` type parameters
of `match`:

```ts
// TS-Pattern v4
match<
  { isAdmin: boolean; plan: 'free' | 'paid' }, // input type
  number // return type
>({ isAdmin, plan })
  .with({ isAdmin: true }, () => 123)
  .with({ plan: 'free' }, () => 'Oops!');
//                              ~~~~~~ โŒ not a number.
```

the main drawback is that you need to set the ***input type***
explicitly ***too***, even though TypeScript should be able to infer it.

In TS-Pattern v5, you can use the `.returnType<Type>()` method to only
set the return type:

```ts
match({ isAdmin, plan })
  .returnType<number>() // ๐Ÿ‘ˆ new
  .with({ isAdmin: true }, () => 123)
  .with({ plan: 'free' }, () => 'Oops!');
//                              ~~~~~~ โŒ not a number.
```

#### What's Changed

- TS-Pattern v5 base branch by
[@&#8203;gvergnaud](https://togithub.com/gvergnaud) in
[gvergnaud/ts-pattern#139

**Full Changelog**:
gvergnaud/ts-pattern@v4.3.0...v5.0.0

###
[`v4.3.0`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v4.3.0)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/788c082e85c3e03374177b253f002fc11c38d059...v4.3.0)

#### TS-Pattern and node16

TS-Pattern now fully supports `moduleResolution: node16`, with both ES
and CommonJS modules. This resolves the long standing issue number
[#&#8203;110](https://togithub.com/gvergnaud/ts-pattern/issues/110).
Special thanks to [@&#8203;Andarist](https://togithub.com/Andarist) and
[@&#8203;frankie303](https://togithub.com/frankie303) for helping me
understand and fix this issue โค๏ธ

#### What's Changed

- build: better support moduleResolution: bundler by
[@&#8203;gvergnaud](https://togithub.com/gvergnaud) in
[gvergnaud/ts-pattern#158
- Gvergnaud/fix build for nodenext and commonjs by
[@&#8203;gvergnaud](https://togithub.com/gvergnaud) in
[gvergnaud/ts-pattern#160

**Full Changelog**:
gvergnaud/ts-pattern@v4.2.2...v4.3.0

###
[`v4.2.3`](https://togithub.com/gvergnaud/ts-pattern/compare/v4.2.2...788c082e85c3e03374177b253f002fc11c38d059)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v4.2.2...788c082e85c3e03374177b253f002fc11c38d059)

###
[`v4.2.2`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v4.2.2)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v4.2.1...v4.2.2)

##### Bug fixes:

- Issue
[#&#8203;142](https://togithub.com/gvergnaud/ts-pattern/issues/142):
Fixes a type inference bug when the input type only has optional
properties. [commit
3c36992](https://togithub.com/gvergnaud/ts-pattern/commit/3c36992)

###
[`v4.2.1`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v4.2.1)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v4.2.0...v4.2.1)

#### Bug fixes

This release fixes inference of `P.array` when the input is a readonly
array (issue
[#&#8203;148](https://togithub.com/gvergnaud/ts-pattern/issues/148))

```ts
declare const input: readonly {
  readonly title: string;
  readonly content: string;
}[];

const output = match(input)
  .with(
    P.array({ title: P.string, content: P.string }),
    //      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //              Used to error, now works 
    (posts) => 'a list of posts!'
  )
  .otherwise(() => 'something else');
```

###
[`v4.2.0`](https://togithub.com/gvergnaud/ts-pattern/releases/tag/v4.2.0)

[Compare
Source](https://togithub.com/gvergnaud/ts-pattern/compare/v4.1.4...v4.2.0)

#### 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:

```ts
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 [@&#8203;Andarist](https://togithub.com/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:

```ts
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:
[gvergnaud/ts-pattern#140

</details>

---

### Configuration

๐Ÿ“… **Schedule**: Branch creation - "after 1pm and before 5pm on Friday"
in timezone Asia/Tokyo, Automerge - At any time (no schedule defined).

๐Ÿšฆ **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

โ™ป **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

๐Ÿ”• **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://www.mend.io/free-developer-tools/renovate/). View
repository job log
[here](https://developer.mend.io/github/turtton/volglass).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNS4xMTcuMyIsInVwZGF0ZWRJblZlciI6IjM3LjgxLjMiLCJ0YXJnZXRCcmFuY2giOiJtYWluIn0=-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants