typescript - “参数”类型上不存在属性“id”
问题描述
我正在使用 Typescript 构建一个快速 API。我设置了带有 id 参数的路由,如下所示:
router.route('/cheeses/:id')
.get(controller.showRoute)
我的控制器如下所示:
export function showRoute(req: Request, res: Response, next: NextFunction): void {
Cheese.findById(req.params.id)
.then((cheese: ICheeseModel) => res.json(cheese))
.catch(next)
}
但是我收到以下错误:
lib/controllers/cheeses.ts:11:30 - error TS2339: Property 'id' does not exist on type 'Params'.
Property 'id' does not exist on type 'string[]'.
11 Cheese.findById(req.params.id)
~~
从我读到的req.params
应该是any
类型,但它似乎被设置为字符串数组。
这是我的 tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"moduleResolution": "node",
"pretty": true,
"sourceMap": true,
"target": "es6",
"outDir": "./dist",
"baseUrl": "./lib"
},
"include": [
"lib/**/*.ts"
],
"exclude": [
"node_modules"
]
}
还有我的 package.json:
{
"name": "typescript-express-api",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"build": "tsc",
"dev": "nodemon",
"start": "node ./dist/server"
},
"dependencies": {
"@types/express": "^4.17.0",
"@types/mongoose": "^5.5.12",
"@types/node": "^12.7.2",
"@types/webrtc": "^0.0.25",
"express": "^4.17.1",
"mongoose": "^5.6.9",
"ts-node": "^8.3.0",
"typescript": "^3.5.3"
}
}
我也在使用 nodemon 来观察开发过程中的变化。这是我的nodemon.json:
{
"watch": ["lib"],
"ext": "ts",
"exec": "ts-node ./lib/app.ts"
}
我试图遵循这种方法:Typescript Error: Property 'user' does not exist on type 'Request',如下所示:
declare namespace Express {
export interface Request {
params: any;
}
}
但它似乎没有任何效果。
解决方案
推荐阅读
- android - Android BiometricPrompt:无法解析符号 PromptInfo
- javascript - 如果找到文本上的任何单词,我该怎么说?
- javascript - 如何对 React Native Reanimated 中的键盘事件做出反应?
- python - 如何分隔没有逗号分隔的字典?
- primefaces - 如何使用 PrimeFaces 设置 ChartJS Axis 标签
- django - 如何使用 django 快速将包含 5000 多行的 excel 文件导入 sqlite 数据库
- forms - 重置表单和验证
- sql - 行集总,周期日期
- python - 在scrapy中没有得到预期的输出
- bash - 强制轮换某个日志文件而不使用 logrotate