Skip to content

Commit 3995003

Browse files
derodero24som-sm
andauthored
ConditionalPick: Fix returning {} instead of never when no keys match (#1359)
Co-authored-by: Som Shekhar Mukherjee <iamssmkhrj@gmail.com>
1 parent f0af103 commit 3995003

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

source/conditional-pick.d.ts

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type {ConditionalKeys} from './conditional-keys.d.ts';
2+
import type {IsNever} from './is-never.d.ts';
23

34
/**
45
Pick keys from the shape that matches the given `Condition`.
@@ -38,9 +39,10 @@ type StringKeysOnly = ConditionalPick<Example, string>;
3839
3940
@category Object
4041
*/
41-
export type ConditionalPick<Base, Condition> = Pick<
42-
Base,
43-
ConditionalKeys<Base, Condition>
44-
>;
42+
export type ConditionalPick<Base, Condition> = ConditionalKeys<Base, Condition> extends infer Keys
43+
? IsNever<Keys> extends true
44+
? never
45+
: Pick<Base, Keys & keyof Base>
46+
: never;
4547

4648
export {};

test-d/conditional-pick.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,10 @@ expectType<{name: string; successes: number; failures: bigint}>(awesomeCondition
2626

2727
declare const exampleConditionalPickWithUndefined: ConditionalPick<Example, string | undefined>;
2828
expectType<{a: string; c?: string}>(exampleConditionalPickWithUndefined);
29+
30+
// Returns `never` when no keys match the condition
31+
declare const noMatchingKeys: ConditionalPick<Example, number>;
32+
expectType<never>(noMatchingKeys);
33+
34+
declare const noMatchingKeys2: ConditionalPick<{a: string; b: number}, boolean>;
35+
expectType<never>(noMatchingKeys2);

0 commit comments

Comments
 (0)