简体   繁体   English

如何使用装饰器覆盖打字稿中类的静态方法

[英]How to use a decorator to overwrite a static method of a class in typescript

Here is what I do in javascript这是我在 javascript 中所做的

class A {
  static foo (a, b, callback) {
    setTimeout(() => {
      let result = doSomethig(a, b)
      callback(result)
    }, 1000)
  }
}

function decorator (OriginalClass) {
  return class extends OriginalClass {
    static foo (a, b) {
      return new Promise((res) => {
        super.foo(a, b, (result) => {
          res(result)
        })
      })
    }
  }
}

@decorator    
class B extends A {
}

let result = await B.foo(10, 20)

I want to overwrite a method of a class, and in the overwritten method, I want to call the original method.我想覆盖一个类的方法,在覆盖的方法中,我想调用原来的方法。 Is there any way to do this in Typescript?有没有办法在打字稿中做到这一点?

You can do something like this:你可以这样做:

class A {
  static bar() {
    console.log("barA");
  }
}

function decorator(OriginalClass: any) {

  let baseBar = OriginalClass.bar;
  OriginalClass.bar = function () {
    baseBar();
    console.log("barOverridden");
  }  
  return OriginalClass;
}

@decorator    
class B extends A {
}

B.bar();
function StaticMethodDecorator(
   target: Function, // the function itself and not the prototype
   propertyKey: string | symbol, // The name of the static method
   descriptor: TypedPropertyDescriptor<any>
) {
   console.log("StaticMethodDecorator called on: ", target, propertyKey, descriptor);
}

class StaticMethodDecoratorExample {
   @StaticMethodDecorator
   static staticMethod() {
   }
}

as described at: https://khru.gitbooks.io/typescript/static_method_decorator.html如以下所述: https : //khru.gitbooks.io/typescript/static_method_decorator.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何允许 class 方法用 Typescript 覆盖? - How to allow class method overwrite with Typescript? Typescript装饰器-将方法装饰器链接到类装饰器 - Typescript decorators - link method decorator to class decorator Typescript类装饰器来扩展方法 - typescript class decorator to extends method Typescript 装饰器:从方法装饰器中获取类装饰器值 - Typescript decorator: get class decorator value from method decorator 具有属性装饰器的TypeScript类的行为就像是静态的 - TypeScript class with property decorator acts as if static 如何在通过 Typescript 中的装饰器添加到 class 的方法中访问“this”? - How do you access `this` in a method added to a class via a decorator in Typescript? 如何通过TypeScript类修饰器在方法中注入额外的变量? - How to inject extra variable in method via typescript class decorator right? 打字稿:一个类方法可以成为另一个方法的装饰器吗? - Typescript: Can a class method be a decorator of another method? Typescript:如何在实例成员属性(mixin)中使用方法装饰器? - Typescript: how to use a method decorator in an instance member property (mixin)? 如何使用TypeScript方法修饰符并保留正常的`this`范围 - How to use a TypeScript method decorator and retain normal `this` scope
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM