Reputation: 12618
I'm trying to get the hang of TypeScript and various guides on how to use node.js and express talk about adding properties to the Request object before passing them down through the middleware.
Of course, for type script these properties have to be defined so I tried to do so in a file called local.d.ts:
/// <reference path="tsd.d.ts" />
import mySql = require('mysql');
declare module Express {
export interface Request {
dbPool: mySql.IPool;
}
}
I then 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 get: "Property 'dbPool' does not exist on type 'Request'." What am I doing wrong?
Upvotes: 4
Views: 3818
Reputation: 556
I know this is old, but lodash's "assign" method seems to work for me, and might be cleaner:
import * as _ from "lodash";
...
app.use(function (req, res, next) {
_.assign(req, {dbPool: pool});
});
Upvotes: 0
Reputation: 1870
As workaround you can inherit interface from express.Request
:
declare module 'mysql' {
import express = require('express');
interface Request extends express.Request {
dbPool: IPool;
}
}
and then cast request in your code:
(<mysql.Request>req).dbPool...
Another option is to remove function declaration from 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;
}
and extend interface as:
declare module 'express' {
import mysql = require('mysql');
interface Express {
dbPool: mysql.IPool;
}
}
but after that you need to cast module before call it:
var exp = <express.Express>(<any>express)();
Upvotes: 3