function log(target: any) { console.log(typeof target) } @log class Valami { } new Valami()
A Valami osztályból semmit nem valósítunk meg, mégis csinál valamit. Kiírja saját a konstruktor típusát.
Az any helyett írhattuk volna Function típust.
Adattag hozzáadása:
const Ageman = (constructor: Function) => { constructor.prototype.age = 43; } @Ageman class Man {} const man = new Man(); console.log(man['age']);
Ahol elkészítem a Man osztály, csak elé írom a @Ageman dekorátort és már van is age adattagja.
function alap() { return function (constructor: Function) { constructor.prototype.fiz = 300; } } @alap() class Dolgozo { } var mari = new Dolgozo(); console.log(mari['fiz'] );
A Dolgozo osztály üres, de kidekoráltuk az @alap() dekorátorral, így már van egy fiz adattagja.
function alapfiz(alap: number) { return function (constructor: Function) { constructor.prototype.fiz = alap; } } @alapfiz(300) class Dolgozo { } var mari = new Dolgozo(); console.log(mari['fiz'] );
function egy() { return function(target: any, propertyKey: string, descriptor: PropertyDescriptor) { console.log('1-s dekorátor') } } class Dolgozo { @egy() valami() {} } var mari = new Dolgozo(); mari.valami();
A valami() metódus üres, de kidkoráltuk az @egy() dekorátorral, így csinál is valamit.
A konzolon megjelenő szöveg:
1-s dekorátor
Szükséges kapcsoló:
{ "compilerOptions": { "experimentalDecorators": true } }
Egy teljesebb tsconfig.json fájl:
{ "compilerOptions": { "rootDir": "src", "target": "es6", "watch": true, "experimentalDecorators": true } }