Last active
January 20, 2021 08:10
-
-
Save rasmuskl/9fb21e012d53f87afc134af8b1ab7f8c to your computer and use it in GitHub Desktop.
TypeScript autobind decorator
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
function autobind<TFunction extends Function>(constructor: TFunction):TFunction { | |
const newConstructor = function(...args) { | |
constructor.apply(this, args); | |
for (const property in this) { | |
if (typeof this[property] !== typeof Function) { | |
continue; | |
} | |
this[property] = this[property].bind(this); | |
} | |
}; | |
newConstructor.prototype = Object.create(constructor.prototype); | |
newConstructor.prototype.constructor = constructor; | |
return newConstructor as any; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment