本文介绍了使用TypeScript扩展Express Request对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图掌握TypeScript以及有关如何使用node.js的各种指南,并表达有关在将属性传递给中间件之前将属性添加到R​​equest对象的讨论.

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.

当然,对于类型脚本,必须定义这些属性,因此我尝试在一个名为local.d.ts的文件中这样做:

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;
});

但是我得到:类型'Request'上不存在属性'dbPool'."我在做什么错了?

But I get: "Property 'dbPool' does not exist on type 'Request'."What am I doing wrong?

推荐答案

作为解决方法,您可以从express.Request继承接口:

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...

另一种选择是从express.d.ts中删除函数声明:

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;
}

并将接口扩展为:

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)();

这篇关于使用TypeScript扩展Express Request对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 09:54