Last change
on this file was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.2 KB
|
Rev | Line | |
---|
[6a3a178] | 1 | /**
|
---|
| 2 | Extract the keys from a type where the value type of the key extends the given `Condition`.
|
---|
| 3 |
|
---|
| 4 | Internally this is used for the `ConditionalPick` and `ConditionalExcept` types.
|
---|
| 5 |
|
---|
| 6 | @example
|
---|
| 7 | ```
|
---|
| 8 | import {ConditionalKeys} from 'type-fest';
|
---|
| 9 |
|
---|
| 10 | interface Example {
|
---|
| 11 | a: string;
|
---|
| 12 | b: string | number;
|
---|
| 13 | c?: string;
|
---|
| 14 | d: {};
|
---|
| 15 | }
|
---|
| 16 |
|
---|
| 17 | type StringKeysOnly = ConditionalKeys<Example, string>;
|
---|
| 18 | //=> 'a'
|
---|
| 19 | ```
|
---|
| 20 |
|
---|
| 21 | To support partial types, make sure your `Condition` is a union of undefined (for example, `string | undefined`) as demonstrated below.
|
---|
| 22 |
|
---|
| 23 | @example
|
---|
| 24 | ```
|
---|
| 25 | type StringKeysAndUndefined = ConditionalKeys<Example, string | undefined>;
|
---|
| 26 | //=> 'a' | 'c'
|
---|
| 27 | ```
|
---|
| 28 | */
|
---|
| 29 | export type ConditionalKeys<Base, Condition> = NonNullable<
|
---|
| 30 | // Wrap in `NonNullable` to strip away the `undefined` type from the produced union.
|
---|
| 31 | {
|
---|
| 32 | // Map through all the keys of the given base type.
|
---|
| 33 | [Key in keyof Base]:
|
---|
| 34 | // Pick only keys with types extending the given `Condition` type.
|
---|
| 35 | Base[Key] extends Condition
|
---|
| 36 | // Retain this key since the condition passes.
|
---|
| 37 | ? Key
|
---|
| 38 | // Discard this key since the condition fails.
|
---|
| 39 | : never;
|
---|
| 40 |
|
---|
| 41 | // Convert the produced object into a union type of the keys which passed the conditional test.
|
---|
| 42 | }[keyof Base]
|
---|
| 43 | >;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.