UNPKG

2.57 kBTypeScriptView Raw
1import type {ArrayEntry, MapEntry, ObjectEntry, SetEntry} from './entry';
2
3type ArrayEntries<BaseType extends readonly unknown[]> = Array<ArrayEntry<BaseType>>;
4type MapEntries<BaseType> = Array<MapEntry<BaseType>>;
5type ObjectEntries<BaseType> = Array<ObjectEntry<BaseType>>;
6type SetEntries<BaseType extends Set<unknown>> = Array<SetEntry<BaseType>>;
7
8/**
9Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entries` type will return the type of that collection's entries.
10
11For example the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries|`Object`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries|`Map`}, {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/entries|`Array`}, and {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/entries|`Set`} collections all have this method. Note that `WeakMap` and `WeakSet` do not have this method since their entries are not enumerable.
12
13@see `Entry` if you want to just access the type of a single entry.
14
15@example
16```
17import type {Entries} from 'type-fest';
18
19interface Example {
20 someKey: number;
21}
22
23const manipulatesEntries = (examples: Entries<Example>) => examples.map(example => [
24 // Does some arbitrary processing on the key (with type information available)
25 example[0].toUpperCase(),
26
27 // Does some arbitrary processing on the value (with type information available)
28 example[1].toFixed()
29]);
30
31const example: Example = {someKey: 1};
32const entries = Object.entries(example) as Entries<Example>;
33const output = manipulatesEntries(entries);
34
35// Objects
36const objectExample = {a: 1};
37const objectEntries: Entries<typeof objectExample> = [['a', 1]];
38
39// Arrays
40const arrayExample = ['a', 1];
41const arrayEntries: Entries<typeof arrayExample> = [[0, 'a'], [1, 1]];
42
43// Maps
44const mapExample = new Map([['a', 1]]);
45const mapEntries: Entries<typeof map> = [['a', 1]];
46
47// Sets
48const setExample = new Set(['a', 1]);
49const setEntries: Entries<typeof setExample> = [['a', 'a'], [1, 1]];
50```
51
52@category Object
53@category Map
54@category Set
55@category Array
56*/
57export type Entries<BaseType> =
58 BaseType extends Map<unknown, unknown> ? MapEntries<BaseType>
59 : BaseType extends Set<unknown> ? SetEntries<BaseType>
60 : BaseType extends readonly unknown[] ? ArrayEntries<BaseType>
61 : BaseType extends object ? ObjectEntries<BaseType>
62 : never;