I want to add userName property to Request object in express using type declaration file .d.ts to be able to set it through middleware and use in other routes.
here is my /src/types/index.d.ts
export declare global {
namespace Express {
interface Request {
userName?: string;
}
}
}
/src/index.ts
...
app.use((req: Request, res: Response, next: NextFunction) => {
req.userName = "anyName";
next();
});
...
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"rootDir": "./src",
"outDir": "./dist"
}
}
The Problem:
- It is working without error for
npx tsc && node ./dist/index.js
- But not working with
nodemon ./src/index.ts
ornpx ts-node ./src/index.ts
The Error: TSError: ⨯ Unable to compile TypeScript: src/index.ts:7:9 - error TS2339: Property 'userName' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. 7 req.userName = "anyName";
I am looking for solution without need to add .d.ts files into tsconfig.json or without using reference directive. If any ...
I want to add userName property to Request object in express using type declaration file .d.ts to be able to set it through middleware and use in other routes.
here is my /src/types/index.d.ts
export declare global {
namespace Express {
interface Request {
userName?: string;
}
}
}
/src/index.ts
...
app.use((req: Request, res: Response, next: NextFunction) => {
req.userName = "anyName";
next();
});
...
tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"rootDir": "./src",
"outDir": "./dist"
}
}
The Problem:
- It is working without error for
npx tsc && node ./dist/index.js
- But not working with
nodemon ./src/index.ts
ornpx ts-node ./src/index.ts
The Error: TSError: ⨯ Unable to compile TypeScript: src/index.ts:7:9 - error TS2339: Property 'userName' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'. 7 req.userName = "anyName";
I am looking for solution without need to add .d.ts files into tsconfig.json or without using reference directive. If any ...
Share Improve this question asked Mar 8 at 17:13 Chirag PatelChirag Patel 381 silver badge6 bronze badges1 Answer
Reset to default 1To inlude and exclude files as defined in tsconfig.json at the time of starting the server, You have to use files option with ts-node as described in ts-node npmjs
use one of the following command to start the server:
npx ts-node --files ./src/index.ts
or
npx nodemon --exec "ts-node --files" ./src/index.ts