1

I am building an express API using Typescript. I have routes set up with a parameter of id like so:

router.route('/cheeses/:id')
  .get(controller.showRoute)

My controller looks like this:

export function showRoute(req: Request, res: Response, next: NextFunction): void {
  Cheese.findById(req.params.id)
    .then((cheese: ICheeseModel) => res.json(cheese))
    .catch(next)
}

However I get the following error:

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)
                                ~~

From what I have read req.params should be any type, but it seems to be set as an array of strings.

This is my tsconfig.json:

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "pretty": true,
    "sourceMap": true,
    "target": "es6",
    "outDir": "./dist",
    "baseUrl": "./lib"
  },
  "include": [
    "lib/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

And my 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"
  }
}

I'm also using nodemon to watch for changes during development. Here's my nodemon.json:

{
  "watch": ["lib"],
  "ext": "ts",
  "exec": "ts-node ./lib/app.ts"
}

I have tried to follow this approach: Typescript Error: Property 'user' does not exist on type 'Request', something like this:

declare namespace Express {
  export interface Request {
    params: any;
  }
}

But it seems to have no effect.

  • Exactly the same problem here. Same ts-node an typescript versions. Problem occurs first 12 hrs ago on a codebase that was not changed for the last year. – JRoppert Aug 19 '19 at 11:26
  • Ah, ok so perhaps it's a new release of something? I'll try rolling back some dependencies... – mickyginger Aug 19 '19 at 13:55
  • Ok, so rolling back to @types/express 4.0.32 fixes the issue. Very surprising since there are 13 more recent versions than that. – mickyginger Aug 19 '19 at 14:20
  • They changed the type of `params` from `any` to `string[]` and to something else a few days later. So it seems to be a moving target currently. Rolling back to a version where `params` are still of type `any` did it form. – JRoppert Aug 22 '19 at 21:00
  • 1
    You do not want this sollution, but you could change your type of `req` to ` any` , like `...function showRoute(req: any, res: Response...` – Nebulosar Aug 17 '21 at 14:12

0 Answers0