Skip to content

Instantly share code, notes, and snippets.

@davemecha
Last active October 18, 2021 13:26
Show Gist options
  • Save davemecha/df3a61629a274e6519e327c7557bc836 to your computer and use it in GitHub Desktop.
Save davemecha/df3a61629a274e6519e327c7557bc836 to your computer and use it in GitHub Desktop.
Typed mapping of a tapescript object to a new object with same keys
type ValueOf<T> = T[keyof T];
// Since I find the typing in record not as convenient I return an object type.
// The record type could be returned as well. Just omit the return type definition.
export function mapObject<IN extends Record<string, unknown>, VAL>(
map: (v: ValueOf<IN>, k: keyof IN) => VAL,
obj: IN,
): { [K in keyof IN]: VAL } {
const result = {} as Record<keyof IN, VAL>;
for (const i in obj) {
if (i in obj) {
result[i] = map(obj[i], i);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment