TypeScript allows-emit decorator metadata which enables more powerful features through reflection. This lesson show what decorators and reflection fit together and how to configure your own decorators to use reflection .
For now, if we look at the compiled file:
var__decorate = ( This&& This. __decorate) | |function(decorators, target, key, desc) {varc = arguments.length, R = C < 3? Target:desc = = =NULL? desc =object.getownpropertydescriptor (target, key): Desc, D; if(typeofReflect = = = "Object" &&typeofReflect.decorate = = = "function") R =reflect.decorate (decorators, target, key, DESC); Else for(vari = 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; returnC > 3 && R &&Object.defineproperty (target, Key, R), R;};functionAddage (age) {return function(targetclass) {return(function () { functionClass_1 () { This. Age =Age ; This. Name =NewTargetclass (). Name; } returnClass_1; }()); };}varPerson = (function () { functionPerson () { This. Name = "Johnn"; } person= __decorate ([Addage ()], person); return Person ;} ());varJohn =NewPerson (); Console.log (John);//{name: "Johnn", age:30}
It decorates addage to the person class.
Now if we enable the "Emitdecoratormetadata" in Tsconfig.json:
{ "CompilerOptions": { "RootDir": "src", "Module": "Commonjs", "Target": "ES5", "Noimplicitany":false, "Sourcemap":false, "OutDir": "./dist", "Noemitonerror":true, "Experimentaldecorators":true, "Emitdecoratormetadata": True }, "Exclude": [ "Node_modules", "Typings/main", "Typings/main.d.ts" ]}
Compile the files again, now we get:
var person = (function () { function person () { this. Name = "Johnn" ; } = __decorate ([ addage (+), __metadata (' design:paramtypes ' , []) ], person); return Person ;} ());
It also add metadata.
Install:
NPM Install Reflect-metadata Crypto--save
Index.html:
<script> system.config ({ packages :{"dist":{ "defaultextension": "JS") , " Main ":" Main " }, " Rxjs ": { " defaultextension ":" JS "} }, Map: { "Lodash": "Https://npmcdn.com/[email protected]", "RXJS": "Node_modules/rxjs" , " Reflect-metadata ":" Node_modules/reflect-metadata/reflect.js ", " crypto ":" node_modules/crypto/ Sha1.js ", } }); System.import ("dist")</script>
Main.ts:
Import ' Reflect-metadata ';
function example () { returnfunction(targetclass) { = Reflect.getmetadata (' Design:paramtypes ', targetclass); Console.log (types); return Targetclass }} @example () class person{ constructor (name:string, Age:number) { }}new person ("John", 10);
So in the example () fucntion, we console logs out types, it'll show:
That is means we were able to make it generic, so the any class that comes through into this example decorator, we can look Up it types and then use those types to modify or pass into the constructor, and return the class decorated however we WA Nt.
[TypeScript] Reflection and Decorator Metadata