Skip to content
Merged
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 .changeset/smooth-news-deliver.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'emery': patch
---

Add `typedObjectFromEntries` utility, and improve `ObjectEntry` type.
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export {
export { castToOpaque } from './opaques';

export { getErrorMessage } from './utils/error';
export { typedEntries, typedKeys } from './utils/object';
export { typedEntries, typedKeys, typedObjectFromEntries } from './utils/object';

// Types
// ------------------------------
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

export type ErrorLike = { message: string };

export type ObjectEntry<T> = { [K in keyof T]: [K, T[K]] }[keyof T];
export type ObjectEntry<T> = { [K in keyof T]-?: [K, T[K]] }[keyof T];

export type Nullish = null | undefined;

Expand Down
11 changes: 10 additions & 1 deletion src/utils/object.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { typedEntries, typedKeys } from './object';
import { typedEntries, typedKeys, typedObjectFromEntries } from './object';

describe('utils/object', () => {
describe('typedEntries', () => {
Expand All @@ -16,4 +16,13 @@ describe('utils/object', () => {
expect(result).toEqual(['foo', 'bar']);
});
});
describe('typedObjectFromEntries', () => {
it('should return the correct object', () => {
const result = typedObjectFromEntries([
['foo', 1],
['bar', 2],
]);
expect(result).toEqual({ foo: 1, bar: 2 });
});
});
});
15 changes: 15 additions & 0 deletions src/utils/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,18 @@ export function typedEntries<T extends object>(value: T) {
export function typedKeys<T extends object>(value: T) {
return Object.keys(value) as Array<keyof T>;
}

/**
* An alternative to `Object.fromEntries()` that avoids type widening. Must be
* used in conjunction with `typedEntries` or `typedKeys`.
*
* @example
* const obj = { name: 'Alice', age: 30 };
* const rebuilt1 = Object.fromEntries(Object.entries(obj));
* // ^? { [k: string]: string | number }
* const rebuilt2 = typedObjectFromEntries(typedEntries(obj));
* // ^? { name: string, age: number }
*/
export function typedObjectFromEntries<T extends object>(entries: ObjectEntry<T>[]) {
return Object.fromEntries(entries) as T;
}
Loading