我试图添加一个属性来表达使用typescript从中间件请求对象。但是,我不知道如何向对象添加额外的属性。如果可能的话,我宁愿不用括号。

我正在寻找一个解决方案,允许我写类似的东西(如果可能的话):

app.use((req, res, next) => {
    req.property = setProperty(); 
    next();
});

当前回答

在尝试了8个左右的答案,没有成功。我终于设法让它与jd291的评论指向3mards回购工作。

在基库中创建一个名为types/express/index.d.ts的文件。在信中写道:

declare namespace Express {
    interface Request {
        yourProperty: <YourType>;
    }
}

并将其包含在tsconfig中。json:

{
    "compilerOptions": {
        "typeRoots": ["./types"]
    }
}

那么你的属性应该在每个请求下都是可访问的:

import express from 'express';

const app = express();

app.get('*', (req, res) => {
    req.yourProperty = 
});

其他回答

如果你尝试了所有的答案,仍然没有得到工作,这里有一个简单的hack

app.use((req, res, next) => {
    (req as any).property = setProperty(); 
    next();
});

这将把req对象转换为任意类型,因此您可以添加任何想要的属性。 请记住,这样做将失去req对象的类型安全性。

所有这些回答在某种程度上似乎都是错误的或过时的。

这在2020年5月对我有效:

在$ {PROJECT_ROOT} / @types /快递/ index.d.ts:

import * as express from "express"

declare global {
    namespace Express {
        interface Request {
            my_custom_property: TheCustomType
        }
    }
}

在tsconfig。Json,添加/合并属性,使:

"typeRoots": [ "@types" ]

欢呼。

我已经改变了响应类型,包括ApiResponse(一个自定义响应对象)response <ApiResponse>

export interface ApiResponse {
    status?: string
    error?: string
    errorMsg?: string
    errorSubject?: string
    response?: any
}

const User = async (req: Request, res: Response<ApiResponse>, next: NextFunction) => {
    try {
        if (!username) return res.status(400).send({ errorMsg: 'Username is empty' })
        /* ... */
    } catch(err){
        /* ... */
    }
}

这就是我在使用Nestjs和Express时的工作方式。截至2020年11月。

创建一个文件:./@types/express- server -static-core/index.d.ts

注意:必须有上面的路径和文件名。这样Typescript声明合并就可以了。

import { UserModel } from "../../src/user/user.model";

declare global{
    namespace Express {
        interface Request {
            currentUser: UserModel
        }
    }
}

将其添加到tsconfig.json中

"typeRoots": [
      "@types",
      "./node_modules/@types",
    ]        

只需将属性添加到req。params对象。

req.params.foo = "bar"