-
-
Notifications
You must be signed in to change notification settings - Fork 543
/
conditional-keys.d.ts
47 lines (38 loc) · 1.28 KB
/
conditional-keys.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import type {IfNever} from './if-never';
/**
Extract the keys from a type where the value type of the key extends the given `Condition`.
Internally this is used for the `ConditionalPick` and `ConditionalExcept` types.
@example
```
import type {ConditionalKeys} from 'type-fest';
interface Example {
a: string;
b: string | number;
c?: string;
d: {};
}
type StringKeysOnly = ConditionalKeys<Example, string>;
//=> 'a'
```
To support partial types, make sure your `Condition` is a union of undefined (for example, `string | undefined`) as demonstrated below.
@example
```
import type {ConditionalKeys} from 'type-fest';
type StringKeysAndUndefined = ConditionalKeys<Example, string | undefined>;
//=> 'a' | 'c'
```
@category Object
*/
export type ConditionalKeys<Base, Condition> =
{
// Map through all the keys of the given base type.
[Key in keyof Base]-?:
// Pick only keys with types extending the given `Condition` type.
Base[Key] extends Condition
// 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];