【问题标题】:Typescript express middleware打字稿快递中间件
【发布时间】:2015-02-18 10:51:55
【问题描述】:

我有一个用于 express 的简单身份验证中间件。它检查标题,如果一切都很酷,它会调用 next()

现在当我在“DoSomething”中时,“this”等于全局而不是“Test”的实例,并且 “this.DoSomeThingPrivate”未定义。

我试过了

DoSomeThingPrivate :() => void;

this.DoSomeThingPrivate = () => {
...
}

模式。但也不行。

import express = require('express');

var app = express();

class Test {    
    constructor() {        
    }

    DoSomething(req:express.Request, res:express.Response, next:Function) :void {       
        this.DoSomeThingPrivate();
    }

    private DoSomeThingPrivate() :void
    {       
    }
}

var test = new Test();

app.use(test.DoSomething);

Relates to this

任何想法...

谢谢

【问题讨论】:

    标签: node.js express typescript


    【解决方案1】:

    以下应该可以正常工作,即对DoSomething而不是DoSomethingPrivate使用粗箭头:

    import * as express from 'express';
    
    var app = express();
    
    class Test {    
        constructor() {        
        }
    
        // important: 
        DoSomething = (req:express.Request, res:express.Response, next:express.NextFunction) => {       
            this.DoSomeThingPrivate();
        }
    
        private DoSomeThingPrivate() :void
        {       
        }
    }
    
    var test = new Test();
    
    app.use(test.DoSomething);
    

    注意:您不需要使用bind。还有https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1

    【讨论】:

    • 你也可以使用express.NextFunction作为next参数。
    • 我认为这种方法比bind好得多。
    • 您可以让编译器通过键入DoSomething 来推断参数类型,如下所示:DoSomething: express.RequestHandler = (req, res, next) => ...
    【解决方案2】:

    您只传递了对函数本身的引用。该函数的实例将是全局的。您需要将函数绑定到test 的实例。

    app.use(test.DoSomething.bind(test));
    

    【讨论】:

    • 感谢老兄的工作。我还在习惯打字稿
    • 不用担心。不过,这不是 Typescript 特有的问题。你会发现这通常发生在 JavaScript 中。
    • 除了这个答案和@basarat 的答案之外,这里还有 [a great description of 'this' in TypeScript][1] 描述了问题的原因、此处提供的解决方案以及选择时的权衡其中之一。 [1]:github.com/Microsoft/TypeScript/wiki/…
    • 双箭头语法 DoSomething = (...params...) => { ...function contents...}.bind 的一个重要论点是双箭头在 TypeScript 中是类型安全的。
    猜你喜欢
    • 2018-04-10
    • 2020-04-19
    • 2021-10-28
    • 2021-12-19
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    相关资源
    最近更新 更多