Skip to content

Instantly share code, notes, and snippets.

@davidkayce
Created July 13, 2021 15:26
Show Gist options
  • Save davidkayce/ae521778fada8a95e9c797b8ecb24c2a to your computer and use it in GitHub Desktop.
Save davidkayce/ae521778fada8a95e9c797b8ecb24c2a to your computer and use it in GitHub Desktop.
// A decorator is a function that can be used to modify/change different properties or methods in a class
// They are used inside/on classes only
// Understanding the orde that they are run is important in using decorators
// Decorators can be used on properties, methods or accessors(getters and setters);
// First argument is the prototype
// Second argument is the key ( the method, accessor or property)
// Third argument is the property descriptor
// We want to use a decorator factory as such that takes in externat arguments
const Logging = (message: string) => {
return (target: any, key: string, desc: PropertyDescriptor): void => {
const method = desc.value;
desc.value = () => {
try {
method();
} catch (e) {
console.error(message);
}
};
};
};
const params = (target: any, key: string, index: number) => {
console.log("key: ", key, " index: ", index);
};
const classDef = (constructor: typeof Boat) => {
console.log("constructor: ", constructor);
};
@classDef
class Boat {
// Note you cannot modify properties with decorators as they are stored on the constructor object
// what is made available to us is the prototype object that contains methods
public color = "red";
get formattedColor(): string {
return `The boat is ${this.color}`;
}
@Logging("Cannot drive this boat")
public drive(@params speed: string, @params driver: string): void {
throw new Error("Cannot drive this car yet");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment