Skip to content

Instantly share code, notes, and snippets.

@rasmuskl
Last active January 20, 2021 08:10
Show Gist options
  • Save rasmuskl/9fb21e012d53f87afc134af8b1ab7f8c to your computer and use it in GitHub Desktop.
Save rasmuskl/9fb21e012d53f87afc134af8b1ab7f8c to your computer and use it in GitHub Desktop.
TypeScript autobind decorator
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