diff --git a/source/index.ts b/source/index.ts index 15ad867..a2c1ca6 100644 --- a/source/index.ts +++ b/source/index.ts @@ -4,3 +4,4 @@ export {isEmpty} from './is-empty.js'; export {assertError} from './assert-error.js'; export {asMutable} from './as-mutable.js'; export {objectKeys} from './object-keys.js'; +export {objectEntries} from './object-entries.js'; diff --git a/source/object-entries.ts b/source/object-entries.ts new file mode 100644 index 0000000..731f2ab --- /dev/null +++ b/source/object-entries.ts @@ -0,0 +1,21 @@ +/** +A strongly-typed version of `Object.entries()`. + +This is useful since `Object.entries()` always returns an array of `Array<[string, T]>`. This function returns a strongly-typed array of the entries of the given object. + +- [TypeScript issues about this](https://github.com/microsoft/TypeScript/pull/12253) + +@example +``` +import {objectEntries} from 'ts-extras'; + +const stronglyTypedEntries = objectEntries({a: 1, b: 2, c: 3}); +//=> Array<['a' | 'b' | 'c', number]> + +const untypedEntries = Object.entries(items); +//=> Array<[string, number]> +``` +*/ +export function objectEntries, Key extends `${Exclude}`>(value: Type): Array<[Key, Type[Key]]> { + return Object.entries(value) as Array<[Key, Type[Key]]>; +} diff --git a/test/object-entries.ts b/test/object-entries.ts new file mode 100644 index 0000000..213efd4 --- /dev/null +++ b/test/object-entries.ts @@ -0,0 +1,15 @@ +import test from 'ava'; +import {expectTypeOf} from 'expect-type'; +import {objectEntries} from '../source/index.js'; + +test('objectEntries()', t => { + type Entry = ['1' | 'stringKey', number | string]; + const entries = objectEntries({ + 1: 123, + stringKey: 'someString', + [Symbol('symbolKey')]: true, + }); + + expectTypeOf(entries); + t.deepEqual(entries, [['1', 123], ['stringKey', 'someString']]); +});