【发布时间】:2021-05-03 10:45:12
【问题描述】:
以下问题类似于: Extend Express Request object using Typescript
我几乎尝试了答案和 cmets 中列出的所有组合,但均未成功。由于那个已经超过 4 岁了,我想再次向社区提问:
在 Express 应用程序中,我将 user 属性附加到中间件 auth 中的请求对象。
// index.ts
import express, { Request, Response } from 'express'
.
.
app.get('/test', auth, (req: Request, res: Response) => {
res.send(welcomeScreen(req.user?.client_name || ''))
})
我收到一个错误:
Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'
这是意料之中的。因此,我想扩展 express.Request 对象的类型定义以接受我的 user 属性,假设在自定义 d.ts 文件中。
但无论我如何尝试去做,我仍然得到同样的错误。
d.ts 文件的内容到底应该是什么?到目前为止,我最好的镜头是:
// custom.d.ts
namespace Express {
export interface Request {
user?: {}
}
}
添加后,user 属性在 IDE 中被识别:
(property) Express.Request.user?: {} | undefined
但我仍然得到相同的编译时错误。
我还需要更改tsconfig 吗?谢谢!
// tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "./compiled",
"rootDir": "./src",
"strict": true,
"moduleResolution": "node",
"typeRoots": ["./types"],
"esModuleInterop": true, "skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
【问题讨论】:
-
可以分享一下ts配置文件吗?
-
“但我仍然遇到同样的运行时错误。”你的意思是编译时错误?并尝试不指定 typeRoots - 只需将其包含在 tsconfig.json 的“包含”的全局中?
-
我更正了这个问题,谢谢。这就是你的意思?
"include": ["./types"],好像不行 -
"include": "src"文件夹,或者如果您的 index.ts 只是在项目根目录中,则将其完全关闭?我认为您不必为此指定typeRoots。
标签: typescript express typescript-typings