1

Duplicated: Extend Express Request object using Typescript

import { Router } from 'express';
import * as uuid from 'uuid';

I'm using typescript 3.6.4. I'm extending the express.Request type because I want to add the id field:

interface request extends Express.Request {
    id: string
}

If I create a post method with a middleware that sets the id:

router.post('/orders', (req: request, _res: express.Response, next) => {req.id = uuid.v1(); next();}, async function (req: request, res: express.Response) {
...
});

But I'm getting an error in req: request

tscongif.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": [
      "es5",
      "es6",
      "dom", 
      "es2017", 
      "esnext.asynciterable"
   ],
    "strict": true,
    "alwaysStrict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,                 
    "strictFunctionTypes": true,              
    "strictPropertyInitialization": false,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "baseUrl": "./src",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,

    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "forceConsistentCasingInFileNames": true,
    "sourceMap": true,
    "outDir": "./dist",
    "removeComments": true
  },
  "exclude": ["node_modules"],
  "include": [
    "./src/**/*", "./src/**/*.tsx", "./src/**/*.ts"
  ]
}
Diego
  • 449
  • 1
  • 6
  • 16

2 Answers2

2

i think you are looking for declaration merging

you are able to merge interfaces. declare in global.d.ts your interface and ts will merge it.

declare global {
  declare module 'express' {
    export interface Request {
      id: string;
    }
  }
}

and than you are able to use it anywhere in your app

const id = Express.request.id;
const anythingElseFromRequestInterface = Express.request.baseUrl;
Juraj Kocan
  • 2,648
  • 1
  • 15
  • 23
0

This one worked for me!

declare module "express" {
  interface Request {
    id: string
  }
}
Hasan Tezcan
  • 1,116
  • 1
  • 11
  • 23