Typescript不能从静态函数中引用this



根据https://github.com/microsoft/TypeScript/issues/6331,在静态中引用this是完全合法的,但是,使用这样的类:

class ZController {
static async b(req: RequestType, res: Response) {
await this.a(req);
}
static async a(req) {
console.log('here')
}
}

结果:

Error: unhandledRejection: Cannot read properties of undefined (reading 'a')
TypeError: Cannot read properties of undefined (reading 'a')
at b (/usr/src/app/controllers/z.ts:24:33)
at Layer.handle [as handle_request] (/usr/src/app/node_modules/express/lib/router/layer.js:95:5)
at next (/usr/src/app/node_modules/express/lib/router/route.js:137:13)
at xxx (/usr/src/app/middlewares/Auth.js:108:17)
at processTicksAndRejections (node:internal/process/task_queues:96:5)

我正在运行Typescript 4.4.2.

为什么会这样?根据我的研究,打字稿应该支持这一点。

在代码的某个地方,您正在传递ZController.b的未绑定副本。这意味着当您调用它时,this将不会绑定到ZController

type Req = {};
type Res = {}
class ZController {
static async b(req: Req, res: Res) {
await this.a(req);
}
static async a(req: Req) {
console.log('here')
}
}
ZController.b({}, {}); // works fine
const zb = ZController.b; // zb is not bound to `ZController`
zb({}, {}); // so here, we see failure... this is undefined
//fix by binding back to ZController
const zb2 = ZController.b.bind(ZController);
zb2({}, {}); // works fine
// or wrapping:
const zb3 = (req: Req, res: Res) => ZController.b(req, res);
zb3({}, {}); // works fine

或者不要在静态方法中使用this

class ZController2 {
static async b(req: Req, res: Res) {
await ZController2.a(req);
}
static async a(req: Req) {
console.log('here2')
}
}
const zb4 = ZController2.b;
zb4({},{}) //works

操场上联系

相关内容

  • 没有找到相关文章

最新更新