Skip to content

Instantly share code, notes, and snippets.

@ryanhaticus
Created September 15, 2021 22:45
Show Gist options
  • Select an option

  • Save ryanhaticus/8663846b5885c16e3271ef5dd8dc4b45 to your computer and use it in GitHub Desktop.

Select an option

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.
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