Skip to content

Instantly share code, notes, and snippets.

@ViliamKopecky
Created August 29, 2024 07:42
Show Gist options
  • Save ViliamKopecky/65c263cee1778e8d4cb9ac002f6e2e59 to your computer and use it in GitHub Desktop.
Save ViliamKopecky/65c263cee1778e8d4cb9ac002f6e2e59 to your computer and use it in GitHub Desktop.
typesafe objectEntries, objectFromEntries
/**
* Utility type to make complex types more readable in tooltips and error messages.
*/
type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
type ObjectEntry<T extends object> = Prettify<{ [K in keyof T]: [K, T[K]] }[keyof T]>;
type FromEntries<T extends Array<[PropertyKey, unknown]>> = {
[K in T[number][0]]: Extract<T[number], [K, unknown]>[1]
};
/**
* Returns an array of key-value pairs from an object.
* @param object The object to convert to entries.
* @returns An array of key-value pairs.
*/
export function objectEntries<T extends object>(
object: T
) {
return Object.entries(object) as Array<ObjectEntry<T>>;
}
/**
* Creates an object from an array of key-value pairs.
* @param entries An array of key-value pairs to convert to an object.
* @returns An object created from the key-value pairs.
*/
export function objectFromEntries<T extends Array<[PropertyKey, unknown]>>(
entries: T
) {
return Object.fromEntries(entries) as Prettify<FromEntries<T>>;
}
// Example usage
const sampleObject = { alpha: 1, beta: "hello", gamma: true };
const entryArray = objectEntries(sampleObject);
// entryArray type: [string, string | number | boolean][]
const reconstructedObject = objectFromEntries(entryArray);
// reconstructedObject type: { alpha: number; beta: string; gamma: boolean }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment