-
-
Notifications
You must be signed in to change notification settings - Fork 16
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Sindre Sorhus <[email protected]>
- Loading branch information
1 parent
cf60bad
commit bfbeff9
Showing
3 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]]>; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']]); | ||
}); |