以下打字稿代码的作用是什么?

以下打字稿代码的作用是什么?

问题描述:

以下代码取自角度源代码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})); 

(name: string): any

表示实现该接口的功能应该被称为常规功能;它被称为name字符串参数并返回any

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

这个装饰接口描述角装饰功能,可同时作为@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) => { ... }; 
} 
+0

如果他们使用的任何属性,而不是它是如何处理的?像'new(name:string):any;' –

+0

@RameshRajendran'@ Attribute'是[参数装饰器](https://www.typescriptlang.org/docs/handbook/decorators.html#parameter-decorators),它被使用作为'构造函数(@Attribute(...)foo)'。我猜'any'是指这个语句,*参数装饰器的返回值被忽略*。当用'new'调用时,装饰器返回Attribute的一个实例,如接口所说。 – estus