Skip to content

Instantly share code, notes, and snippets.

@MarwanShehata
Last active April 4, 2025 18:45
Show Gist options
  • Save MarwanShehata/68a698cdbd5393570697566bd87a1b9b to your computer and use it in GitHub Desktop.
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
// 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