Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,21 @@ const builder = <a, b>(
])
).run(),

exhaustive: () => run(),
exhaustive: <c>(handler?: (notMatchedValue: unknown) => c) => {
if (!handler) {
return run();
}
return builder<a, PickReturnValue<b, c>>(
value,
cases.concat([
{
test: () => true,
handler,
select: (value) => value,
},
])
).run();
},

run,
};
Expand Down
7 changes: 6 additions & 1 deletion src/types/Match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ export type Match<
* */
exhaustive: DeepExcludeAll<i, patternValueTuples> extends infer remainingCases
? [remainingCases] extends [never]
? () => PickReturnValue<o, inferredOutput>
? ExhaustiveResult<o, inferredOutput>
: NonExhaustiveError<remainingCases>
: never;

Expand All @@ -152,3 +152,8 @@ type DeepExcludeAll<a, tuple extends [any, any]> = DeepExclude<
a,
tuple extends any ? InvertPatternForExclude<tuple[0], tuple[1]> : never
>;

interface ExhaustiveResult<o, inferredOutput> {
(): PickReturnValue<o, inferredOutput>;
<c>(handler: (notMatchedValue: unknown) => c): PickReturnValue<o, Union<inferredOutput, c>>;
}
17 changes: 17 additions & 0 deletions tests/exhaustive-match.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -868,4 +868,21 @@ describe('exhaustive()', () => {
.with({ t: 'b' }, (x) => 'ok')
.exhaustive();
});


it('accepts fallback to exhaustive', () => {

const input: 'a' | 'b' = 'c' as any;
const value = match(input)
.with('a', x => x)
.with('b', x => x)
.exhaustive(v => ['unexpected', v] as const);

// check return type
const shoulBe: readonly ['unexpected', unknown] | 'a' | 'b' = value;
// @ts-expect-error
const shouldNotBe: 'a' | 'b' = value;

expect(value).toStrictEqual(['unexpected', 'c']);
});
});