【问题标题】:What does the following typescript code do?以下打字稿代码有什么作用?
【发布时间】:2018-05-31 17:14:28
【问题描述】:

以下代码取自 Angular 源代码,di.ts

export interface AttributeDecorator { 
  (name: string): any;
  new (name: string): Attribute;
}

我知道这是一个界面。但是new (name: string): Attribute 在做什么以及为什么名称有两种类型,string and any

上面的代码后面跟着

export interface Attribute { attributeName?: string; }
export const Attribute: AttributeDecorator = makeParamDecorator('Attribute', (attributeName?: string) => ({attributeName}));

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    (name: string): any 表示实现该接口的函数应该作为常规函数调用;它使用name 字符串参数调用并返回any

    new (name: string): Attribute表示实现该接口的函数应该用作构造函数,用new调用并返回Attribute对象。

    这个装饰器接口描述了 Angular 装饰器函数可以用作 @Attribute(...) parameter decorator 函数和 new Attribute(...) 构造函数,并且在这样调用时它们的行为不同。

    new Attribute(...)可用于ES5和ES6中的注解,如this answer所示。

    这个接口描述并由makeParamDecorator工厂创建的函数应该大致像这样工作:

    // decorator factory
    const MyAttributeDecorator = function (attributeName?: string) {
      if (new.target)
        // Attribute object
        return { attributeName };
      else
        // parameter decorator
        return (target, prop, paramIndex) => { ... };
    }
    

    【讨论】:

    • 如果他们使用any而不是Attribute,它如何处理?喜欢new (name: string): any;
    • @RameshRajendran @Attributeparameter decorator,它被用作constructor(@Attribute(...) foo)。我猜any指的是这个语句,参数装饰器的返回值被忽略。当使用new 调用时,装饰器返回一个属性实例,如接口所述。
    猜你喜欢
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    相关资源
    最近更新 更多