typescriptexpressnodemonts-nodetypescript-declarations

Typescript type declaration .d.ts not working with nodemon(ts-node)


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:

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 ...


Solution

  • To 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