Last active
June 5, 2024 17:39
-
-
Save colelawrence/c6d0e719ad703f8b3d7f5ed42c0c50ab to your computer and use it in GitHub Desktop.
Record mapping as a map function (e.g. `[P in keyof T]: Transform<T[P]>`)
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
export function objMap<T extends Record<string, any>, U>( | |
template: T, | |
eachKey: <P extends Extract<keyof T, string>>(name: P, value: T[P]) => U, | |
): { | |
[P in Extract<keyof T, string>]: U; | |
} { | |
// @ts-ignore | |
return Object.fromEntries( | |
Object.entries(template) | |
.filter(([name]) => typeof name === "string") | |
.map(([name, value]) => { | |
// @ts-ignore | |
return [name, eachKey(name, value)]; | |
}), | |
); | |
} |
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
export function objMapWithProxy<T extends Record<string, any>, U>( | |
template: T, | |
eachKey: <P extends Extract<keyof T, string>>(name: P, value: T[P]) => U, | |
): { | |
[P in keyof T]: U; | |
} { | |
return new Proxy(template, { | |
get(target, prop, receiver) { | |
type P = Extract<keyof T, string>; | |
if (typeof prop === "string") { | |
return eachKey(prop as P, Reflect.get(target, prop, receiver) as T[P]); | |
} | |
return undefined; | |
}, | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment