2017-12-18 91 views
2

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

回答

2
(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