Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better Object.entries #167

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@
"types": "./dist/storage.d.ts",
"import": "./dist/storage.mjs",
"default": "./dist/storage.js"
},
"./object-entries": {
"types": "./dist/object-entries.d.ts",
"import": "./dist/object-entries.mjs",
"default": "./dist/object-entries.js"
}
},
"keywords": [],
Expand Down
3 changes: 3 additions & 0 deletions src/entrypoints/object-entries.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
interface ObjectConstructor {
entries<T>(o: T): T extends ArrayLike<any> ? { [K in Extract<keyof T, number>]: [`${K}`, T[K]] }[number][] : { [K in keyof T]: [K, T[K]] }[keyof T][];
}
1 change: 1 addition & 0 deletions src/entrypoints/recommended.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
/// <reference path="set-has.d.ts" />
/// <reference path="map-has.d.ts" />
/// <reference path="array-index-of.d.ts" />
/// <reference path="object-entries.d.ts" />
27 changes: 27 additions & 0 deletions src/tests/object-entries.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { doNotExecute, Equal, Expect } from './utils';

doNotExecute(async () => {
const result1 = Object.entries({ a: 1, b: 2, c: 3 } as const);
const result2 = Object.entries({ a: true, b: 'string', c: { field: 1 } } as const);
const result3 = Object.entries([1, 2, 3] as const);

type tests = [
// Basic functionality test
Expect<Equal<typeof result1, (['a', 1] | ["b", 2] | ['c', 3])[]>>,
// Complex values
Expect<Equal<typeof result2, (['a', true] | ['b', 'string'] | ['c', { readonly field: 1 }])[]>>,
// Array
Expect<Equal<typeof result3, [`${number}`, 1 | 2 | 3][]>>,
];
});

doNotExecute(async () => {
const array = [1, 2, 3];
const readonlyArray = [1, 2, 3] as const;
const result1 = Object.entries(array);
const result2 = Object.entries(readonlyArray);

// Make sure arrays' index is a string in the result
result1[0][0] satisfies `${number}`;
result2[0][0] satisfies `${number}`;
});