Difference between revisions of "TypeScript - Class Decorator Practical Tutorial"

(Created page with " The class decorator is created in an own function with the "target.prototype" of the class decorator. You can then add the class decorator through an annotation "@". Exampl...")
 
(No difference)

Latest revision as of 16:09, 24 May 2020


The class decorator is created in an own function with the "target.prototype" of the class decorator. You can then add the class decorator through an annotation "@". Example: "@Car" when your class decorator is called "Car".


A practical example

function Car(target: Function): void {
	target.prototype.car = function(): void {
		alert("This is a car.");
	}
}

@Car
class Vehicle {
	constructor() {
		console.log("Load vehicle. Additional implemention...");
	}
}
let vehicleObject: any = new Vehicle();
vehicleObject.car();

The class "Vehicle" does get a decorator class "Car" which extends it with a method "car". This method "car" displays an alert with the text "This is a car.".