Typescript方法装饰器:这是未定义的

时间:2019-04-13 14:24:11

标签: typescript decorator typescript-decorator

我正在尝试使用打字稿装饰器,如方法装饰器中的问题所述,此选项未设置为任何内容(未定义)。

在下面的代码中,我试图创建一个控制器装饰器,该控制器装饰器将在控制器类上创建一个koa-router。方法装饰器将包装该方法,并使用koa上下文对其进行调用。

index.ts:

import koa, { ParameterizedContext } from "koa";
import koarouter from "koa-router";

const app = new koa();

function Controller<T extends new (...args: any[]) => {}>(path: string) {
  return (controller: T) => {
    const router = new koarouter({ prefix: path });
    if (controller.prototype.routes) {
      const routes = controller.prototype.routes;
      Object.entries(routes).forEach((e) => {
        if (e[0] === "GET") {
          Object.entries(e[1]).forEach((r) => {
            router.get(r[0], r[1]);
          });
        }
      });
    }
    return class extends controller {
      public router: koarouter = router;
    };
  };
}

function HttpGet(path: string): MethodDecorator {
  // tslint:disable-next-line: only-arrow-functions
  return function(
    target: any,
    propertyName: string | symbol,
    descriptor: PropertyDescriptor,
  ) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: any[]): any {
      return originalMethod(...args);
    };
    if (!target.routes) {
      target.routes = { GET: {}, POST: {} };
    }
    target.routes.GET = { ...target.routes.GET, [path]: descriptor.value };
    return descriptor;
  };
}

// tslint:disable-next-line: max-classes-per-file
@Controller("/adex")
class AdexController {
  constructor(private msg: string = "") {
    this.allAdexs = this.allAdexs.bind(this);
  }
  @HttpGet("/id")
  public allAdexs(ctx: ParameterizedContext) {
    console.log(this);
    ctx.body = `hi from adex ${this.msg}`;
  }
}

const adexController = new AdexController();

app.use(adexController.router.routes());
app.use(adexController.router.allowedMethods());

app.listen(3000);

tsconfig.json:

{
  "exclude": ["node_modules"],
  "include": ["src"],
  "compilerOptions": {
    /* Basic Options */
    "target": "es2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "declaration": true /* Generates corresponding '.d.ts' file. */,
    "sourceMap": true /* Generates corresponding '.map' file. */,
    "outDir": "./lib" /* Redirect output structure to the directory. */,
    "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
    "strict": false /* Enable all strict type-checking options. */,
    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
    "paths": {
      "@/*": ["src/*"]
    },
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
    "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
    "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */
  }
}

2 个答案:

答案 0 :(得分:1)

接受的答案不是真的。如果您在装饰器中定义一个函数并将其分配给 descriptor.value,则调用时它将绑定到 this

export function someDecorator() {
    return function (
        object: Object, propertyName: string, descriptor: PropertyDescriptor
    ): void {
        const originalFunction = descriptor.value;
        descriptor.value = function () {
            // here you have access to `this`:
            return originalFunction.bind(this)();
        };
    };
}

答案 1 :(得分:0)

我的代码中的问题是JavaScript中的经典问题,我在类外使用类方法并尝试访问此方法。这个问题无法解决,我试图做的事情是根本不可能的,要构造一个koa-router,我需要一个控制器实例,并且该实例上的方法需要绑定到该实例,这在类中是不可能的或方法装饰器,当装饰器代码运行时,我们还没有实例。 我更改了设计,从尝试在装饰器中构造路由器以将该任务委托给另一个类,该类将在运行时执行此任务,并让装饰器仅对类进行注释。