Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

From C # to TypeScript-decorator

2025-03-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

From C # to TypeScript-decorator

In C #, if you don't want to modify the class or method directly, but add some additional information or function to the class or method, you can think of using Attribute, which is a very convenient function decorator.

With TypeScript, you can also use decorators to add additional functionality to classes, functions, properties, and parameters. The decorator is a proposal of ES7, and there is already an implementation available in TypeScript, but you need to enable experimentalDecorators in tsconfig.json.

"compilerOptions": {..., / / other options "experimentalDecorators": true} decorator introduction

Decorators in TypeScript can be applied to classes, methods, properties, and function parameters, and multiple can be applied at the same time.

The decorator is written as @ name (), () you don't need it, or you can write some parameters in it.

@ Testable@Log ('controller') class Controller {@ GET getContent (@ QueryParam arg: string): implementation of the string {return';}} decorator

Decorators can be divided into two types according to the implementation:

One is without parentheses, just like an attribute, such as @ Testable.

Function Testable (target: Function) {/ / the parameters of classes, methods, properties, and method parameters are different / / here you can record some information to target, or do some processing for target, such as seal}

The other is parenthesized, just like a function, such as @ Log ('controller'), where the arguments in the implementation function are parenthesized and need to return a function.

Function Log (name: string) {/ / name is the incoming parameter 'controller' return function (target: Function) {/ / the parameters of classes, methods, properties, and method parameters are different / / here you can do some processing}} class decorator according to name and target

The above (target: Function) is actually the decorator parameter of the class, pointing to the constructor of the class. If you want to add a simple seal function to the class, you can do this:

Function sealed (target: Function) {Object.seal (target); Object.seal (target.prototype);} @ sealedclass Test {} Test.prototype.test =''; / / Runtime error and cannot be added

The sealed above is the class decorator, the target refers to the constructor, and the class decorator has only one parameter.

Method decorator

The method decorator is used in a similar way to the class decorator, except that the parameters are different. The method decorator has three parameters:

If you decorate a static method, it is the constructor of the class, and if it is an instance method, it is the prototype of the class.

The name of the method.

PropertyDescriptor of the method.

PropertyDescriptor is the attribute descriptor, which has

Whether configurable can be configured, such as dynamically adding and deleting function properties

Whether writable is writable or not, it can be used to set read-only properties.

Whether enumerable can be enumerated, that is, whether it can be enumerated to the

The value of a value object or property

With these parameters, you can add some functions to the method, such as the routing of Get in the type WebApi as follows:

Const Router = Symbol (); / / unique key, function GET (path?: string) {/ / GET takes an optional parameter return (target: any, name: string) = > setMethodDecorator (target, name, 'GET', path);} / / save method and path, function setMethodDecorator (target: any, name: string, method: string, path?: string) {target [Router] = target [Router] | | {} Target [Router] [name] = target [Router] [name] | | {}; target [Router] [name]. Method = method; target [Router] [name]. Path = path;} / / set enumerablefunction Enumerable (enumerable: boolean) {return (target: any, name: string, descriptor: PropertyDescriptor) > {descriptor.enumerable = enumerable;} through PropertyDescriptor } class Controller {@ GET @ Enumerable (true) getContent (arg: string): string {return'';}} Parameter decorator

Method parameters can also have decorators, there are also three parameters, the first two parameters are consistent with the method, and the last parameter is the location of the decorated parameter.

The parameter decorator can dynamically check or set parameter values for the method. The following is to check whether the parameter is empty or throw an exception.

Const CheckNullKey = Symbol (); const Router = Symbol (); / / save the parameters of CheckNull decoration function CheckNull (target: any, name: string, index: number) {target [Router] = target [Router] | {}; target [Router] [name] = target [Router] [name] | {}; target [Router] [name]. Params = target [Router] [name]. Params | []; target [Router] [name] .params [index] = CheckNullKey } / / find the parameter of CheckNull and check the parameter value. If it is empty, throw an exception, otherwise continue to execute the method function Check (target: any, name: string, descriptor: PropertyDescriptor) {let method = descriptor.value; descriptor.value = function () {let params = target [Router] [name] .params; if (params) {for (let index = 0; index < params.length) Index++) {if (params [index] = = CheckNullKey & & / / find the parameter of CheckNull and throw an exception (arguments [index] = undefined | | arguments [index] = null) {throw new Error ("Missing required argument.");} return method.apply (this, arguments) }} class Controller {@ Check getContent (@ CheckNull id: string): string {console.info (id); return id;}} new Controller () .getContent (null); / / error: Missing required argument. Attribute decorator

The usage is the same as above, there are only two parameters, like the first two of the class decorator, are often used to identify the properties of the property.

Function Column (target: any, name: string) {/ / save the name. This column is only identified as a column in the corresponding database, which is commonly used in the ORM framework} class Table {@ Column name: string;}

There is also a decorator for the property accessor, which is basically the same as the method, with the same three parameters, but there can only be one get and set for the same property, and it must be the one declared first.

Class User {private _ name: string; @ Enumerable (true) get name () {return this._name;} set name (value: string) {this._name = value;}} execution order of multiple decorators

Multiple decorators can be added to a declaration, so there will be an order of execution.

First execute the decorator function from top to bottom, and then apply the function returned by the parenthesized decorator from the bottom up.

Function Test1 () {console.info ('eval test1'); return function (target: any, name: string, descriptor: PropertyDescriptor) {console.info (' apply test1');}} function Test2 () {console.info ('eval test2'); return function (target: any, name: string, descriptor: PropertyDescriptor) {console.info (' apply test2');}} class User1 {@ test1 () @ Test2 getName () {}}

The result is:

Eval test1eval test2apply test2apply test1

In short, the decorator is tantamount to the introduction of natural decoration patterns, adding additional functions to classes, methods, etc. However, the decorator is not very stable at present, but because it is really convenient, there are mature projects in use.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report