Skip to content

Commit

Permalink
fix: repair typescript not complaining of missing keys
Browse files Browse the repository at this point in the history
  • Loading branch information
lukemorales committed Feb 12, 2023
1 parent f9e9331 commit d210075
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 19 deletions.
7 changes: 7 additions & 0 deletions .changeset/thin-panthers-know.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"exhaustive": patch
---

Fix exhaustive compile checks

With the added support of exhaustive boolean checks, TypeScript stopped complaining if a key was missing in the exhaustive object due to how the new types were declared. The types were adjusted to bring back the expected behavior of TypesScript complaining at compile-time if you forget to handle all the use-cases.
33 changes: 14 additions & 19 deletions src/exhaustive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,27 @@ import { corrupt } from './corrupt';

type AnyFunction = (...args: any[]) => unknown;

export type ExhaustiveUnion<Union extends string | boolean> =
Union extends string
? {
[Key in Union]: (value: Key) => any;
} & ExhaustiveFallback
: Union extends boolean
? {
[Key in `${Union}`]: (value: Key extends 'true' ? true : false) => any;
} & ExhaustiveFallback
: never;
export type ExhaustiveUnion<Union extends string | boolean> = {
[Key in `${Union}`]: (
value: Key extends 'true' ? true : Key extends 'false' ? false : Key,
) => any;
} & ExhaustiveFallback;

export type ExhaustiveTag<
Union extends object,
Tag extends keyof Union,
Values extends Union[Tag] = Union[Tag],
> = Values extends string
> = Union[Tag] extends string | boolean
? {
[Key in Values]: (value: Extract<Union, { [K in Tag]: Key }>) => any;
} & ExhaustiveFallback
: Values extends boolean
? {
[Key in `${Values}`]: (
[Key in `${Union[Tag]}`]: (
value: Extract<
Union,
{ [K in Tag]: Key extends 'true' ? true : false }
{
[K in Tag]: Key extends 'true'
? true
: Key extends 'false'
? false
: Key;
}
>,
) => any;
} & ExhaustiveFallback
Expand Down Expand Up @@ -80,7 +76,6 @@ function exhaustive(
const unionObject = unionOrObject as object;
const keyofUnion = matchOrKeyofUnion as keyof typeof unionObject;

// @ts-expect-error super generic overload implementation will fallback to never
return exhaustive.tag(unionObject, keyofUnion, match);
}

Expand Down

0 comments on commit d210075

Please sign in to comment.