1 type MapKey<BaseType> = BaseType extends Map<infer KeyType, unknown> ? KeyType : never;
2 type MapValue<BaseType> = BaseType extends Map<unknown, infer ValueType> ? ValueType : never;
4 export type ArrayEntry<BaseType extends readonly unknown[]> = [number, BaseType[number]];
5 export type MapEntry<BaseType> = [MapKey<BaseType>, MapValue<BaseType>];
6 export type ObjectEntry<BaseType> = [keyof BaseType, BaseType[keyof BaseType]];
7 export type SetEntry<BaseType> = BaseType extends Set<infer ItemType> ? [ItemType, ItemType] : never;
10 Many 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.
12 For 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.
14 @see `Entries` if you want to just access the type of the array of entries (which is the return of the `.entries()` method).
18 import {Entry} from 'type-fest';
24 const manipulatesEntry = (example: Entry<Example>) => [
25 // Does some arbitrary processing on the key (with type information available)
26 example[0].toUpperCase(),
28 // Does some arbitrary processing on the value (with type information available)
32 const example: Example = {someKey: 1};
33 const entry = Object.entries(example)[0] as Entry<Example>;
34 const output = manipulatesEntry(entry);
37 const objectExample = {a: 1};
38 const objectEntry: Entry<typeof objectExample> = ['a', 1];
41 const arrayExample = ['a', 1];
42 const arrayEntryString: Entry<typeof arrayExample> = [0, 'a'];
43 const arrayEntryNumber: Entry<typeof arrayExample> = [1, 1];
46 const mapExample = new Map([['a', 1]]);
47 const mapEntry: Entry<typeof map> = ['a', 1];
50 const setExample = new Set(['a', 1]);
51 const setEntryString: Entry<typeof setExample> = ['a', 'a'];
52 const setEntryNumber: Entry<typeof setExample> = [1, 1];
55 export type Entry<BaseType> =
56 BaseType extends Map<unknown, unknown> ? MapEntry<BaseType>
57 : BaseType extends Set<unknown> ? SetEntry<BaseType>
58 : BaseType extends unknown[] ? ArrayEntry<BaseType>
59 : BaseType extends object ? ObjectEntry<BaseType>