2017-08-14 126 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装饰者似乎为时过早。”* - 我不会这么说,您只需要了解他们的架构限制和所需的解决方法。至于方法装饰器,_“不起作用”_是什么意思?运行时没有任何反应?编译错误? –