Skip to content

Commit

Permalink
Merge pull request #207 from gvergnaud/gvergnaud/fix-exhaustive-match…
Browse files Browse the repository at this point in the history
…ing-on-readonly-arrays

fix(readonly): exhaustive matching on readonly array
  • Loading branch information
gvergnaud committed Dec 3, 2023
2 parents e36debe + 16786f0 commit 8f2158f
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 14 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ts-pattern",
"version": "5.0.5",
"version": "5.0.6",
"description": " The exhaustive Pattern Matching library for TypeScript.",
"type": "module",
"source": "src/index.ts",
Expand Down
2 changes: 0 additions & 2 deletions src/types/ExtractPreciseValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ export type ExtractPreciseValue<a, b> = b extends Override<infer b1>
: // inlining IsAny for perf
0 extends 1 & a
? b
: b extends readonly []
? []
: b extends readonly any[]
? ExtractPreciseArrayValue<a, b, IsReadonlyArray<a>>
: b extends Map<infer bk, infer bv>
Expand Down
17 changes: 9 additions & 8 deletions src/types/Match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ export type Match<
with<
const p extends Pattern<i>,
c,
value extends MatchedValue<i, InvertPattern<p, i>>,
excluded = InvertPatternForExclude<p, value>
value extends MatchedValue<i, InvertPattern<p, i>>
>(
pattern: IsNever<p> extends true
? /**
Expand All @@ -52,12 +51,14 @@ export type Match<
selections: FindSelected<value, p>,
value: value
) => PickReturnValue<o, c>
): Match<
Exclude<i, excluded>,
o,
[...handledCases, excluded],
Union<inferredOutput, c>
>;
): InvertPatternForExclude<p, value> extends infer excluded
? Match<
Exclude<i, excluded>,
o,
[...handledCases, excluded],
Union<inferredOutput, c>
>
: never;

with<
const p1 extends Pattern<i>,
Expand Down
13 changes: 12 additions & 1 deletion tests/readonly.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { match } from '../src';
import { P, match } from '../src';
import { Equal, Expect } from '../src/types/helpers';

describe('readonly', () => {
Expand Down Expand Up @@ -71,5 +71,16 @@ describe('readonly', () => {
})
.exhaustive();
});

it('must support exhaustive matching on readonly arrays', () => {
const sum = (xs: readonly number[]): number =>
match(xs)
.with([], (x) => {
type t = Expect<Equal<typeof x, readonly []>>;
return 0;
})
.with([P._, ...P.array()], ([x, ...xs]) => x + sum(xs))
.exhaustive();
});
});
});

0 comments on commit 8f2158f

Please sign in to comment.