ts-decorators-utils
What is it ?
Create the typescript decorator declaratively, Just like Java.
It also provides tools to implement 'reflection'
It can run on the web or in nodejs
Getting Start
install
npm i ts-decorator-utils
tsconfig.json
{ "compilerOptions": { "outDir": "./dist", "module": "commonjs", "target": "es6", "declaration": true, "lib": [ "es6", "dom", "esnext" ], "experimentalDecorators": true, "emitDecoratorMetadata": true, "strictNullChecks": true }, "exclude": [ "node_modules", "dist" ]}
Notice 'experimentalDecorators' and 'emitDecoratorMetadata'
Create a decorator
Create the required location, parameters, and metadata
; .class.method.property.parameter.build; ; ; .propertytypeof option === 'string' ? ) .parameter .build;
Use decorators
Getting information is similar to Java reflection
; // Is there a specified decorator on the target on the class, Some will return true or Object, and none will return undefinedconsole.logDecoratorUtil.getMetadataDemo, TestClass; // trueconsole.logDecoratorUtil.getMetadataDemo, TestClass, 'staticMethod'; // trueconsole.logDecoratorUtil.getMetadataDemo, TestClass, 'staticProp'; // trueconsole.logDecoratorUtil.getMetadataDemo, TestClass.prototype, 'prop'; // trueconsole.logDecoratorUtil.getMetadataDemo, TestClass.prototype, 'method'; // true console.logDecoratorUtil.getMetadataDemo, TestClass.prototype; // undefinedconsole.logDecoratorUtil.getMetadataDemo, TestClass, 'staticMethod2'; // undefined console.logDecoratorUtil.getMethodsTestClass; // [ [ 'staticMethod', [ [Function: String] ], undefined ] ]
Demo1
; .property.parameter.build; console.logDecoratorUtil.getMetadataValue, Demo.prototype, 'a'; // trueconsole.logDecoratorUtil.getMetadataValue, Demo.prototype, 'test'; // undefinedconsole.logDecoratorUtil.getMetadataValue, Demo.prototype, 'test', 0; // true ; // is a Symbol Type
; .method.class.build; console.logDecoratorUtil.getMetadataValue2, Demo2; // demo2console.logDecoratorUtil.getMetadataValue2, Demo2.prototype, 'test'; // testconsole.logDecoratorUtil.getMetadataValue2, Demo2, 'testStatic'; // testStatic // 可以获得类中 使用装饰器的实例方法 集合console.logDecoratorUtil.getMethodsDemo2.prototype; // [ [ 'test', [ [Function: String] ], [Function: Date] ] ]// 可以获得类中 使用装饰器的实例属性 集合 返回类型 [string, Constructor][]console.logDecoratorUtil.getPropertiesDemo2.prototype; // []// 可以获得类中 使用装饰器的静态属性 集合 返回类型 [string, Constructor[], Constructor][] 数组中元组对应 方法名,方法参数类型数组,方法返回类型console.logDecoratorUtil.getMethodsDemo2; // [ [ 'testStatic', [ [Function: Number] ], undefined ] ]// 可以获得类中 使用装饰器的静态属性 集合console.logDecoratorUtil.getPropertiesDemo2; // []