Created
March 3, 2017 16:36
-
-
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.
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 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