如何在打字稿编译装饰(注释)? [英] How are decorators (annotations) compiled in Typescript?

查看:262
本文介绍了如何在打字稿编译装饰(注释)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角2,我可以创造一个组成部分,是这样的:

 进口{组件,模板}从'angular2 / angular2@零件({
  选择:我的组件
})
@视图({
  内联:< D​​IV>你好,我的名字是{{名}}< / DIV>中
})
出口类MyComponent的{
  构造函数(){
    this.name ='最大'
  }
  说我的名字() {
    的console.log(我的名字是',this.name)
  }
}

(来源: http://blog.ionic.io/angular-2-系列组件/

这是再编译成定期ES5。

我的问题是两部分:


  1. 这些装饰是特定角度。它们是如何定义的?

  2. 如何定义自己的装饰?


解决方案

在事实上,你应该叫注释的装饰,因为它是略低不同;-)他们让装饰对象。本博客文章可以给这里一些提示:<一href=\"http://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html\" rel=\"nofollow\">http://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html.

所以装饰不能具体到角的东西。没有为ES7的建议,他们也被打字稿语言本身的支持。这可以在conjonction用于与反映元数据(的库它包含到 angular2-polyfills.js 文件)设置和获取元数据元素。


  • 类装饰

     导出功能MyClassDecorator(价值:字符串){
      复位功能(目标:功能){
        Reflect.defineMetadata(MyClassDecorator,价值目标);
      }
    }@零件({ ... })
    @MyClassDecorator(我的元数据)
    出口类AppComponent {
      构造函数(){
        让decoratorValue:字符串
          = Reflect.getMetadata(MyClassDecorator,this.constructor);
      }
    }


  • 功能装饰

     导出功能日志(目标:对象,
                    PROPERTYKEY:字符串,
                    描述:TypedPropertyDescriptor&LT;&任何GT;){
      VAR originalMethod = descriptor.value;  descriptor.value =功能(参数... args:任何[]){
        的console.log(以下简称方法ARG游戏:+ JSON.stringify(参数));
        VAR的结果= originalMethod.apply(这一点,参数);
        的console.log(返回值是:+结果);
        返回结果;
      };  返回描述;
    }出口类AppComponent {
      构造函数(){}  @MyMethodDecorator
      的getMessage(){
        返回测试;
      }
    }


  • 参数装饰

     导出功能MyParameterDecorator(参数1){
      返回功能(目标:有,methodKey:串符号|
                      parameterIndex:数字){
        (......)
      };
    }


  • 类物业装饰

     导出功能MyPropertyDecorator(目标:有,
            PROPERTYKEY:字符串|符号){
      (......)
    }


因此​​,在一般的一个装饰对应于函数。如果没有需要返回的包装的,如果不使用参数。如果您想使用参数装饰你需要一个额外的函数来获取参数和返回actualy装饰:

  //在参数装饰的情况下,
// myMethod的(@MyDecoratorWithoutParameter someParam){...}
导出功能MyDecoratorWithoutParameter(目标:有,
    PROPERTYKEY:字符串|符号,parameterIndex:号码){
  的console.log('装饰叫做');
}// myMethod的(@MyDecoratorWithParameter(测试)someParam){...}
导出功能MyDecoratorWithParameter(参数1){
  //参数1包含了测试
  返回功能(目标:有,PROPERTYKEY:串符号|
                  parameterIndex:数字){
    的console.log('装饰叫做');
  };
}

下面是对应我的样本plunkr: https://plnkr.co/编辑/ 0VBthTEuIAsHJjn1WaAX?p = preVIEW

下面是可以给你打字稿的更多详细信息的链接:

希望它可以帮助你,
蒂埃里

In Angular 2, I can create a component, like this:

import {Component, Template} from 'angular2/angular2'

@Component({
  selector: 'my-component'
})
@View({
  inline: "<div>Hello my name is {{name}}</div>"
})
export class MyComponent {
  constructor() {
    this.name = 'Max'
  }
  sayMyName() {
    console.log('My name is', this.name)
  }
}

(source: http://blog.ionic.io/angular-2-series-components/)

This is then compiled into regular ES5.

My question is in 2 parts:

  1. These decorators are specific to Angular. How are they defined?
  2. How do I define my own decorators?

解决方案

In fact, you should call "annotations" decorators since it's slighty different ;-) They allow to decorate objects. This blog post can give some more hints here: http://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html.

So decorators aren't something specific to Angular. There is a proposal for ES7 and they are also supported by the TypeScript language itself. This can be used in conjonction with the reflect-metadata library (it's contained into the angular2-polyfills.js file) to set and get metadata for elements.

  • Class decorator

    export function MyClassDecorator(value: string) {
      return function (target: Function) {
        Reflect.defineMetadata("MyClassDecorator", value, target);
      }
    }
    
    @Component({ ... })
    @MyClassDecorator("my metadata")
    export class AppComponent {
      constructor() {
        let decoratorValue: string
          = Reflect.getMetadata("MyClassDecorator", this.constructor);
      }
    }
    

  • Function decorator

    export function log(target: Object,
                    propertyKey: string,
                    descriptor: TypedPropertyDescriptor<any>) {
      var originalMethod = descriptor.value;
    
      descriptor.value = function(...args: any[]) {
        console.log("The method args are: " + JSON.stringify(args));
        var result = originalMethod.apply(this, args);
        console.log("The return value is: " + result);
        return result;
      };
    
      return descriptor;
    }
    
    export class AppComponent {
      constructor() { }
    
      @MyMethodDecorator
      getMessage() {
        return 'test';
      }
    }
    

  • Parameter decorator

    export function MyParameterDecorator(param1) {
      return function(target: any, methodKey: string | symbol,
                      parameterIndex: number) {
        (...)
      };
    }
    

  • Class property decorator

    export function MyPropertyDecorator(target: any,
            propertyKey: string | symbol) {
      (...)
    }
    

So in general a decorator corresponds to a function. If there is no need to return a wrapping one if you don't use parameter. If you want to use parameters for the decorator you need an additional function to get parameters and return the actualy decorator:

// In the case of a parameter decorator
// myMethod(@MyDecoratorWithoutParameter someParam) { ... }
export function MyDecoratorWithoutParameter(target: any,
    propertyKey: string | symbol, parameterIndex: number) {
  console.log('decorator called');
}

// myMethod(@MyDecoratorWithParameter('test') someParam) { ... }
export function MyDecoratorWithParameter(param1) {
  // param1 contains 'test'
  return function(target: any, propertyKey: string | symbol,
                  parameterIndex: number) {
    console.log('decorator called');
  };
}

Here is a plunkr corresponding to my samples: https://plnkr.co/edit/0VBthTEuIAsHJjn1WaAX?p=preview.

Here are links that could give you more details with TypeScript:

Hope it helps you, Thierry

这篇关于如何在打字稿编译装饰(注释)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆