Last active
March 30, 2023 13:12
-
-
Save karol-majewski/dc979192186df66c1580a569c194e53a to your computer and use it in GitHub Desktop.
Decorator that binds class methods compatible with TypeScript 5.0
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 bound<This extends object, Args extends any[], Return>( | |
target: (this: This, ...args: Args) => Return, | |
context: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Return> | |
) { | |
const methodName = String(context.name); | |
if (context.private) { | |
throw new Error(`${bound.name} cannot decorate private properties like ${methodName}.`); | |
} | |
context.addInitializer(function () { | |
Object.assign(this, { [methodName]: target.bind(this)}) | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
TypeScript Playground
Official documentation