类型“ Params”上不存在属性“ id”

时间:2019-08-19 09:19:38

标签: typescript express

我正在使用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;
  }
}

但这似乎没有效果。

0 个答案:

没有答案