Last active
April 4, 2025 18:45
-
-
Save MarwanShehata/68a698cdbd5393570697566bd87a1b9b to your computer and use it in GitHub Desktop.
This snippet demonstrates how to use a custom class decorator in TypeScript to dynamically enhance a class by adding new properties and methods. The `@Component` decorator injects a `uniqueID` and an `insertInDOM` method into the target class, showc
This file contains hidden or 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
// TS Decorators | |
function Component(constructor: Function) { | |
// here we can do something like add/modify/enhance/delete properties from class methods | |
constructor.prototype.uniqueID = Math.random(); | |
constructor.prototype.insertInDOM = () => { | |
console.log(`Inserting component in DOM`); | |
}; | |
} | |
// now every instance of class ProfileComponent will have uniqueID and insertInDOM | |
// we can instead do this by using classes with extends | |
// class Component { | |
// public uniqueID: number; | |
// public insertInDOM(): void { | |
// console.log(`Inserting component in DOM`); | |
// } | |
// } | |
@Component | |
class ProfileComponent {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment