Saturday, June 3, 2023

TypeScript map for objects

In another round of React experiments, after another Vue frustration with Volar not typing event arguments, I was again into the state normalization land. When dealing with objects with IDs as keys, every operation requires a tedious reduce, in contrast to the intuitive map we use with arrays.

So I wrote a map for objects:

function mapObj<T>(obj: Record<string, T>, callback: (elem: T, key: string) => T): Record<string, T> {
	return Object.keys(obj).reduce((accum, key) => {
		accum[key] = callback(obj[key], key);
		return accum;
	}, {} as Record<string, T>);
}

It’s fully typed, and it was surprisingly easy to write. TypeScript is a great language.

No comments: