Skip to content

Commit

Permalink
Add objectEntries() (#12)
Browse files Browse the repository at this point in the history
Co-authored-by: Sindre Sorhus <[email protected]>
  • Loading branch information
younho9 and sindresorhus authored Nov 29, 2021
1 parent cf60bad commit bfbeff9
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions source/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
21 changes: 21 additions & 0 deletions source/object-entries.ts
Original file line number Diff line number Diff line change
@@ -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<Type extends Record<PropertyKey, unknown>, Key extends `${Exclude<keyof Type, symbol>}`>(value: Type): Array<[Key, Type[Key]]> {
return Object.entries(value) as Array<[Key, Type[Key]]>;
}
15 changes: 15 additions & 0 deletions test/object-entries.ts
Original file line number Diff line number Diff line change
@@ -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<Entry[]>(entries);
t.deepEqual(entries, [['1', 123], ['stringKey', 'someString']]);
});

0 comments on commit bfbeff9

Please sign in to comment.