Having a NodeJs app with Express and Typescript, I am attempting to extend the Request type from Express.
I have created an index.d.ts file with the following code snippet:
import { User } from "models/user";
declare global {
namespace Express {
export interface Request {
currentUser: User
}
}
}
Although my code editor (VSCode) indicates that everything is fine and autocomplete is working correctly, TypeScript throws an error at runtime:
src/api/controllers/post.controller.ts:60:24 - error TS2339: Property 'currentUser' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.
To resolve this issue, I came across the following code snippet which solved my problem:
import { User } from 'models/user';
declare module "express-serve-static-core" {
export interface Request {
currentUser: User
}
}
I had to place this code in any file within my app for it to work. However, I am still puzzled as to why this solution works while the initial one does not. Can anyone provide an explanation?
I am running my app using the ts-node package with the command ts-node ./src/index.ts
Here is my tsconfig.json file:
{
"compilerOptions": {
"target": "ES2016",
"module": "commonjs",
"strict": true,
"baseUrl": "./src",
"typeRoots": [
"./src/@types",
"./node_modules/@types"
],
"types": ["reflect-metadata"],
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": [
"node_modules"
]
}