Extending an Express Request Object with TypeScript

I am trying to get a TypeScript widget and various guides on how to use node.js and talk about adding properties to the Request object before passing them through middleware.

Of course, for the script type, these properties must be defined, so I tried to do this in the local.d.ts file:

/// <reference path="tsd.d.ts" />
import mySql = require('mysql');
declare module Express {
    export interface Request {
        dbPool: mySql.IPool;
    }
}

Then I will try to call it from my main code file:

/// <reference path="typings/tsd.d.ts" />
/// <reference path="typings/local.d.ts" />
...
import express = require('express');
...
var pool = mySql.createPool({
    user: "username",
    ...
});
app.use(function (req, res, next) {
    req.dbPool = pool;
});

But I understand: "The" dbPool "property does not exist in the" Request "type." What am I doing wrong?

+4
source share
2 answers

As a workaround, you can inherit the interface from express.Request:

declare module 'mysql' {
    import express = require('express');

    interface Request extends express.Request {
        dbPool: IPool;
    }
}

:

(<mysql.Request>req).dbPool...

- express.d.ts:

declare module "express" {
    import * as http from "http";

    //- function e(): e.Express;
    //-
    //- module e {

        interface I_1 {
        }

        ...

        interface I_N {
        }

    //- }
    //-
    //- export = e;
}

:

declare module 'express' {
    import mysql = require('mysql');

    interface Express {
        dbPool: mysql.IPool;
    }
}

, :

var exp = <express.Express>(<any>express)();
+3

, , lodash "", , :

import * as _ from "lodash";

...

app.use(function (req, res, next) {
    _.assign(req, {dbPool: pool});
});
0

All Articles