Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesmh/1554619a41d3bbfafa06e55016a0bd0d to your computer and use it in GitHub Desktop.
Save jamesmh/1554619a41d3bbfafa06e55016a0bd0d to your computer and use it in GitHub Desktop.
TypeScript decorator to bind constructor arguments as object properties with the same names / keys as the parameter names.
export default (constructor: any) => {
const functionString = constructor.toString();
const params = GetArgumentNames(functionString);
const newConstructor: any = function (...args) {
const newObj = new constructor(args);
params.map((param, index) => newObj[param] = args[index]);
return newObj;
}
newConstructor.prototype = constructor.prototype;
return newConstructor;
}
const RegExInsideParentheses = /[(][^)]*[)]/;
const RegExParenthesesAndSpaces = /[()\s]/g;
const GetArgumentNames = functionString => RegExInsideParentheses.exec(functionString)[0].replace(RegExParenthesesAndSpaces, "").split(',').map(str => str.trim());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment