UNPKG

2.85 kBTypeScriptView Raw
1type MapKey<BaseType> = BaseType extends Map<infer KeyType, unknown> ? KeyType : never;
2type MapValue<BaseType> = BaseType extends Map<unknown, infer ValueType> ? ValueType : never;
3
4export type ArrayEntry<BaseType extends readonly unknown[]> = [number, BaseType[number]];
5export type MapEntry<BaseType> = [MapKey<BaseType>, MapValue<BaseType>];
6export type ObjectEntry<BaseType> = [keyof BaseType, BaseType[keyof BaseType]];
7export type SetEntry<BaseType> = BaseType extends Set<infer ItemType> ? [ItemType, ItemType] : never;
8
9/**
10Many collections have an `entries` method which returns an array of a given object's own enumerable string-keyed property [key, value] pairs. The `Entry` type will return the type of that collection's entry.
11
12For 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.
13
14@see `Entries` if you want to just access the type of the array of entries (which is the return of the `.entries()` method).
15
16@example
17```
18import type {Entry} from 'type-fest';
19
20interface Example {
21 someKey: number;
22}
23
24const manipulatesEntry = (example: Entry<Example>) => [
25 // Does some arbitrary processing on the key (with type information available)
26 example[0].toUpperCase(),
27
28 // Does some arbitrary processing on the value (with type information available)
29 example[1].toFixed(),
30];
31
32const example: Example = {someKey: 1};
33const entry = Object.entries(example)[0] as Entry<Example>;
34const output = manipulatesEntry(entry);
35
36// Objects
37const objectExample = {a: 1};
38const objectEntry: Entry<typeof objectExample> = ['a', 1];
39
40// Arrays
41const arrayExample = ['a', 1];
42const arrayEntryString: Entry<typeof arrayExample> = [0, 'a'];
43const arrayEntryNumber: Entry<typeof arrayExample> = [1, 1];
44
45// Maps
46const mapExample = new Map([['a', 1]]);
47const mapEntry: Entry<typeof mapExample> = ['a', 1];
48
49// Sets
50const setExample = new Set(['a', 1]);
51const setEntryString: Entry<typeof setExample> = ['a', 'a'];
52const setEntryNumber: Entry<typeof setExample> = [1, 1];
53```
54
55@category Object
56@category Map
57@category Array
58@category Set
59*/
60export type Entry<BaseType> =
61 BaseType extends Map<unknown, unknown> ? MapEntry<BaseType>
62 : BaseType extends Set<unknown> ? SetEntry<BaseType>
63 : BaseType extends readonly unknown[] ? ArrayEntry<BaseType>
64 : BaseType extends object ? ObjectEntry<BaseType>
65 : never;