Skip to content

Commit

Permalink
ConditionalKeys: Fix filtering out never type (#881)
Browse files Browse the repository at this point in the history
  • Loading branch information
roryabraham committed May 25, 2024
1 parent 0f73237 commit 863511d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 5 additions & 3 deletions source/conditional-keys.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type {IfNever} from './if-never';

/**
Extract the keys from a type where the value type of the key extends the given `Condition`.
Expand Down Expand Up @@ -36,10 +38,10 @@ export type ConditionalKeys<Base, Condition> =
[Key in keyof Base]-?:
// Pick only keys with types extending the given `Condition` type.
Base[Key] extends Condition
// Retain this key since the condition passes.
? Key
// Retain this key
// If the value for the key extends never, only include it if `Condition` also extends never
? IfNever<Base[Key], IfNever<Condition, Key, never>, Key>
// Discard this key since the condition fails.
: never;

// Convert the produced object into a union type of the keys which passed the conditional test.
}[keyof Base];
4 changes: 4 additions & 0 deletions test-d/conditional-keys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,14 @@ type Example = {
b?: string | number;
c?: string;
d: Record<string, unknown>;
e: never;
};

declare const exampleConditionalKeys: ConditionalKeys<Example, string>;
expectType<'a'>(exampleConditionalKeys);

declare const exampleConditionalKeysWithUndefined: ConditionalKeys<Example, string | undefined>;
expectType<'a' | 'c'>(exampleConditionalKeysWithUndefined);

declare const exampleConditionalKeysTargetingNever: ConditionalKeys<Example, never>;
expectType<'e'>(exampleConditionalKeysTargetingNever);

0 comments on commit 863511d

Please sign in to comment.