2017-08-14 102 views
2

這裏使用新的ECMAScript裝飾是我的代碼示例:不能在打字稿2.4.2

function enumerable(value: boolean) { 
    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { 
    descriptor.enumerable = value; 
    }; 
} 

class A { 
    @enumerable(false) 
    a: number = 1 
    b: number = 2 

    myMethod() {} 
} 

const a = new A() 

無論我嘗試,我得到:

D:(real path removed)/first-try-typescript>tsc --emitDecoratorMetadata --experimentalDecorators decorators.ts 
decorators.ts(8,3): error TS1240: Unable to resolve signature of property decorator when called as an expression. 

我已經嘗試了從同一stackoferflow問題的建議:

  • 加入emitDecoratorMetadata & experimentalDecorators到tsconfig
  • 運行TSC --emitDecoratorMetadata --experimentalDecorators
  • 加入:any標記裝飾函數返回值
  • 加入descriptor: TypedPropertyDescriptor<any>

我總是得到這個錯誤。在終端和Webstorm代碼提示中。方法裝飾器 - 同樣的事情(見下面的例子)。

function test(target: Object, 
       propertyKey: string, 
       descriptor: TypedPropertyDescriptor<any>): any { 
    return descriptor; 
} 

class A { 
    a: number = 1 
    b: number = 2 

    @test 
    myMethod() {} 
} 

const a = new A() 

到目前爲止代碼是在這裏 - https://github.com/rantiev/first-try-typescript

+0

什麼是你想要的結果?裝飾器應該應用於函數/方法,你正在試圖做似乎是混合的方法爲一類 –

+0

@NickTomlin - 這是不正確,裝飾器可以應用到一個屬性爲好。 –

+0

@JohnWeisz啊有趣,我的壞話呢! –

回答

0

不幸的是,物業裝飾沒有訪問屬性描述符,作爲屬性住在類實例,而裝飾在之前的任何評價實例可能存在。此外,您只能對屬性修飾器使用以下簽名:

function (target: any, propKey: string | symbol) 

因此,在此沒有描述符。

你也可以不只是做Object.defineProperty(target, propKey.toString, { enumerable: false, value: ... }),因爲這會在跨越一個實例設置屬性會泄漏到另一個類,即所有實例共享。

實現你在做什麼是可能的,雖然,但有點複雜。我通常做的是創建,只是在時間創建所需的屬性描述符的原型吸氣。喜歡的東西:

function enumerable(value: boolean) { 
    return function (target: any, propKey: string | symbol) { 
     Object.defineProperty(target, propKey, { 
      get: function() { 
       // In here, 'this' will refer to the class instance. 
       Object.defineProperty(this, propKey.toString(), { 
        value: undefined, 
        enumerable: value 
       }); 
      }, 
      set: function (setValue: any) { 
       // In here, 'this' will refer to the class instance. 
       Object.defineProperty(this, propKey.toString(), { 
        value: setValue, 
        enumerable: value 
       }); 
      } 
     }); 
    }; 
} 

「外」的get/set功能將只運行一次,以實例屬性將陰影它的屬性描述符已在實例創建後。

+0

你的屬性裝飾器的例子確實有效。現在開始使用prop裝飾器似乎爲時尚早。解決這個問題我已經注意到屬性裝飾器還不支持的信息(似乎他們有一些問題),另一方面,babel沒有使用prop裝飾器的示例以及https://babeljs.io/docs/plugins/transform -decorators/ – Rantiev

+0

但是,什麼應該工作 - 方法裝飾器,不打字我的身邊打字,找不到問題。 – Rantiev

+0

*「現在開始使用prop裝飾者似乎爲時過早。」* - 我不會這麼說,您只需要瞭解他們的架構限制和所需的解決方法。至於方法裝飾器,_「不起作用」_是什麼意思?運行時沒有任何反應?編譯錯誤? –