Created
September 15, 2021 22:45
-
-
Save ryanhaticus/8663846b5885c16e3271ef5dd8dc4b45 to your computer and use it in GitHub Desktop.
Wrote this code to turn class instances with getters and setters into objects and back. Uses the dangerous eval() function. No current straightforward way to do this in JavaScript or TypeScript. Here's my implementation.
This file contains hidden or 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
| const setClassFromObject = (object: any, instance: any) => { | |
| Object.keys(object).forEach((key) => { | |
| eval(`instance.${key} = object[key]`); | |
| }); | |
| }; | |
| const getObjectFromClassInstance = <T>(instance: any): any => { | |
| const keys = Object.getOwnPropertyNames(Object.getPrototypeOf(instance)) | |
| .map((key) => [ | |
| key, | |
| Object.getOwnPropertyDescriptor(Object.getPrototypeOf(instance), key), | |
| ]) | |
| .filter( | |
| ([key, descriptor]) => | |
| // @ts-expect-error | |
| typeof descriptor.get === 'function' && | |
| // @ts-expect-error | |
| typeof descriptor.set === 'function' | |
| ) | |
| .map(([key]) => key) as string[]; | |
| let resultant = {}; | |
| keys.forEach((key) => { | |
| // @ts-expect-error | |
| resultant[key] = eval(`instance.${key}`); | |
| }); | |
| return resultant as T; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment