如何为为响应添加属性的中间件编写TypeScript定义?

nki*_*int 5 middleware typing node.js express typescript

我想用TypeScript 使用express-boom for express.它缺乏打字,所以我想写自己的.只是让它编译是微不足道的.

这个中间件res用一个属性boom(从boom模块派生)装饰对象:

var express = require('express');
var boom = require('express-boom');

var app = express();

app.use(boom());

app.use(function (req, res) {
  res.boom.notFound(); // Responsds with a 404 status code
});
Run Code Online (Sandbox Code Playgroud)

但随着打字稿我要投它,因为无论http.ServerResponseExpress.Response拥有繁荣的财产,当然是:

return (<any>res).boom.badRequest('bla bla bla');
Run Code Online (Sandbox Code Playgroud)

这是最干净的方法吗?哪些其他类型的中间件正在做类似的事情?

Tim*_*rry 4

还有很多其他 Express 中间件可以用作示例,例如Method-Override及其类型定义

作为一个更具体的示例,如果您想将此 .boom 属性添加到响应对象,您应该只需要创建一个类型定义 (express-boom.d.ts),其中包含:

declare namespace Express {
    interface Boom {
        // Add boom's properties in here
    }

    export interface Response {
        boom: Boom
    }
}
Run Code Online (Sandbox Code Playgroud)