TypeScript 在TypedPropertyDescriptor中使用装饰器时,类型变量会导致编译错误,

ny6fqffe  于 8个月前  发布在  TypeScript
关注(0)|答案(3)|浏览(79)

TypeScript版本: 3.6.3
搜索词: TypedPropertyDescriptor, MethodDecorator, TS2345, 属性'value'的类型不兼容。
代码

  1. type MyDynamicDescriptor = <T>(input: T) => T
  2. type MyStaticDescriptor = (input: number) => number
  3. function dynamicDecorator(foo: string) {
  4. return (_: any, __: any, descriptor: TypedPropertyDescriptor<MyDynamicDescriptor>) => {
  5. console.log('foo:', foo)
  6. console.log('descriptor.value:', descriptor.value)
  7. }
  8. }
  9. function staticDecorator(foo: string) {
  10. return (_: any, __: any, descriptor: TypedPropertyDescriptor<MyStaticDescriptor>) => {
  11. console.log('foo:', foo)
  12. console.log('descriptor.value:', descriptor.value)
  13. }
  14. }
  15. class myClass {
  16. @dynamicDecorator('bar')
  17. myMethod(input: number): number {
  18. return input + 42
  19. }
  20. @staticDecorator('bar')
  21. myOtherMethod(input: number): number {
  22. return input + 42
  23. }
  24. }

预期行为:

dynamicDecoratorstaticDecorator 都没有编译错误。

实际行为:

dynamicDecorator 有编译错误:

  1. error TS2345: Argument of type 'TypedPropertyDescriptor<(input: number) => Promise<number>>' is not assignable to parameter of type 'TypedPropertyDescriptor<MyDynamicDescriptor>'.
  2. Types of property 'value' are incompatible.
  3. Type '((input: number) => Promise<number>) | undefined' is not assignable to type 'MyDynamicDescriptor | undefined'.
  4. Type '(input: number) => Promise<number>' is not assignable to type 'MyDynamicDescriptor'.

** playground链接**

uqcuzwp8

uqcuzwp81#

myMethod 不是通用标识方法。

dffbzjpn

dffbzjpn2#

myMethod should be generic as type MyDynamicDescriptor

  1. @dynamicDecorator('bar')
  2. myMethod<T>(input: T): T {
  3. if (typeof input === 'number') {
  4. return (input + 42) as T;
  5. }
  6. return input;
  7. }
tag5nh1u

tag5nh1u3#

你需要更新MyDynamicDescriptor的类型以匹配myMethod方法的值类型。在这种情况下,你可以将MyDynamicDescriptor to (input: number) => number.更改为其他值。这将允许dynamicDecorator函数中的描述符参数接受一个具有类型(input: number) => number的属性描述符,该类型与myMethod方法兼容。

相关问题