Home > database >  i cannot declare new property in request object of express
i cannot declare new property in request object of express

Time:06-03

I'm trying to attach the new property to the request object in typescript. this is the code :

import { request, Request, response, Response } from "express";

((req: Request, res: Response) => {
    console.log(req.user);
})(request, response)

i'm declaring like this :

declare global {
   namespace Express {
      interface Request {
         user: string;
      }
   }
}

and then I'm running it with ts-node. result is :

/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:843
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
x.ts:9:21 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

9     console.log(req.user);
                      ~~~~

    at createTSError (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:843:12)
    at reportTSError (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:847:19)
    at getOutput (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1057:36)
    at Object.compile (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1411:41)
    at Module.m._compile (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1596:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Object.require.extensions.<computed> [as .ts] (/home/mahdi/Desktop/learn-stuf/test/node_modules/ts-node/src/index.ts:1600:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:827:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
  diagnosticCodes: [ 2339 ]
}

I tested too many answers of sites, but one of them did not work. please help.

CodePudding user response:

  1. First, I think your declare file got some problems. edit the file like
export {}

declare global {
   namespace Express {
      interface Request {
         user: string;
      }
   }
}

or

namespace Express {
  interface Request {
    user?: string
  }
}

  1. add directory that contains the declare file in tsconfig. Since I usually name it express.d.ts and place in src/types folder, in my case, tsconfig.json will be edited like this
{
  "compilerOptions": {
    "typeRoots": ["src/types"],
  }
}

  1. lastly, also add ts-node configuration in tsconfig.json. (not in compilerOptions)
{
  "ts-node": {
    "files": true
  }
}

CodePudding user response:

Are you maybe looking for @types/express ?

You can also fix it with intersection type :

function endpoint (req: Request, res: Response & {user: string;}) {
  console.log(req.user);
}

But maybe you are looking for req.body.user, type Response<{user: string;}> ?

  • Related