Last active
October 18, 2021 13:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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