Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaration merging doesn't work with express 4.17.* Request type

I want to add a property to the Request type, so I created a folder @types/express and in this folder I've added file index.d.ts with this content.

namespace Express {
  interface Request {
    user: number;
  }
}

In VSCode the error has gone while I'm referencing to req.user, and it even shows that user is of type number screenshot that shows that "user" property on the "Request" object is treated right

but when I start the server I see the error that says this:

/home/myself/web/my-server/node_modules/ts-node/src/index.ts:434
    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ⨯ Unable to compile TypeScript:
src/app.ts:46:7 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

46   req.user;
         ~~~~

    at createTSError (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:434:12)
    at reportTSError (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:438:19)
    at getOutput (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:578:36)
    at Object.compile (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:775:32)
    at Module.m._compile (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:858:43)
    at Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Object.require.extensions.<computed> [as .ts] (/home/myself/web/my-server/node_modules/ts-node/src/index.ts:861:12)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)

I'd appreciate any ideas on how to fix it.

p.s. I have done the same with express-session module and added a counter property into the Session interface, and it works flawlessly

like image 221
Sap Green Avatar asked Oct 27 '25 02:10

Sap Green


1 Answers

With @types/express installed (@types/express-session is sufficient, too), this should work:

index.d.ts:

declare module '@types/express-serve-static-core' {
  interface Request {
    user?: User
  }
}

The important part is that the declaration merging logic for this is part of @types/express-serve-static-core (see https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express-serve-static-core/index.d.ts).


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!