TypeScript Tutorial in Hindi #38 - Decorators | TypeScript Decorator basics
Decorators in TypeScript
What are decorators?
How to use it ?
Example with class and property
Interview Question
In TypeScript, decorators are a special kind of declaration that can be attached to classes, methods, properties, or parameters to modify their behaviour.
@Logger
class Person {
constructor(public name: string) {}
}
decorator.ts
function classLogger(constructor:Function){
console.log(constructor.name);
}
function getKeyDetails(target:any,key:any){
console.log(key.name);
}
@classLogger
class CustomMaths{
@getKeyDetails
private value1:number;
value2:number;
constructor(x:number,y:number){
this.value1=x;
this.value2=y;
}
}
var cm1 = new CustomMaths(10,20);
decorator.js
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
function classLogger(constructor) {
console.log(constructor.name);
}
function getKeyDetails(target, key) {
console.log(key.name);
}
let CustomMaths = class CustomMaths {
value1;
value2;
constructor(x, y) {
this.value1 = x;
this.value2 = y;
}
};
__decorate([
getKeyDetails
], CustomMaths.prototype, "value1", void 0);
CustomMaths = __decorate([
classLogger
], CustomMaths);
var cm1 = new CustomMaths(10, 20);