代码之家  ›  专栏  ›  技术社区  ›  lilezek

限制方法修饰符的使用

  •  1
  • lilezek  · 技术社区  · 7 年前

    class A {
      @deco() // This should work.
      public async works() { }
      @deco() // This should fail.
      public fails() { }
    }
    

    我试图这样定义装饰师:

    export function deco() {
      return <T extends {[K in keyof T]: () => Promise<any>}, 
              K extends string>
             (target: T, 
              propertyKey: K, 
              descriptor: PropertyDescriptor) => {
        // Decorator code here.
      };
    }
    

    但它不起作用。这两个方面都失败了 works fails K [K in keyof T] K K extends string propertyKey: K K 不限于T的键。

    这也不起作用:

    export function deco() {
      return <T extends {[K in keyof T]: () => Promise<any>}, 
              K extends keyof T>
             (target: T, 
              propertyKey: K, 
              descriptor: PropertyDescriptor) => {
        // Decorator code here.
      };
    }
    

    这两者都不是:

    export function deco() {
      return <T, 
              K extends keyof T>
             (target: T & {[propertyKey]: () => Promise<any>}, 
              propertyKey: K, 
              descriptor: PropertyDescriptor) => {
        // Decorator code here.
      };
    }
    

    知道吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    7 年前

    您应该使用方法装饰器,而不是属性装饰器:

    declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
    

    function TypeRestrictedMethodDecorator(
        target: Object, // The prototype of the class
        propertyKey: string, // The name of the method
        descriptor: TypedPropertyDescriptor<(... p:any[]) => Promise<any>>
        ) {
        console.log("TypeRestrictedMethodDecorator called on: ", target, propertyKey, descriptor);
    }
    
    class TypeRestrictedMethodDecoratorExample {
        @TypeRestrictedMethodDecorator
        method(num: number): Promise<number> {
            return new Promise((res, rej)=> res(10));
        }
    
        @TypeRestrictedMethodDecorator // Error
        method2(num: number): number {
            return 10;
        }
    }
    

    样本修改自 here