简体   繁体   English

使用声明合并失败扩展快递 object

[英]Extending express object using Declaration merging failing

I am trying to add some properties to the Express/Request object, and everything seems fine but when I try to compile with tsc I get this error: error TS2339: Property 'id' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.我正在尝试向 Express/Request object 添加一些属性,一切似乎都很好,但是当我尝试使用 tsc 编译时出现此错误: error TS2339: Property 'id' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

I've tried all the answers found in this post Extend Express Request object using Typescript , but none of them seem to work for me.我已经尝试了使用 Typescript 在这篇文章 Extend Express Request object 中找到的所有答案,但它们似乎都不适合我。

In my root folder I created this:在我的根文件夹中,我创建了这个:

 @types/express/index.d.ts declare module Express { export interface Request { id: number user_spotify_id: string access_token: string refresh_token: string } }

I also added the types folder to the tsconfig.json file:我还将类型文件夹添加到 tsconfig.json 文件中:

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

This is my callback function for the controller:这是我对 controller 的回调 function:

 async getPlaylists(req: Request, res: Response) { const { id } = req const query = `SELECT * FROM playlist WHERE user_id = $1` const { rows: playlists }: { rows: IPlaylistAll[] } = await db.query(query, [id]) return res.json(playlists[0]) },

I am able to get the id from the request object, and it even says the type is number, but when compiling I get the error I mentioned before.我可以从请求 object 中获取 id,它甚至说类型是数字,但是在编译时我得到了我之前提到的错误。

Look, I was with this problem, I managed to solve it by changing the --transpileOnly flag to --transpile-only in package.json, check the version you are using of TypeScript, mine is 3.9.6.看,我遇到了这个问题,我设法通过将 package.json 中的--transpileOnly标志更改为--transpile-only来解决它,检查您使用的 Z558B544CF685F3936.7ZC903B 版本是 3E。

And it was not necessary to configure tsconfig.json for min.并且没有必要至少配置 tsconfig.json。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM