0

I am getting the following error when running ts-node.

I defined d.ts as follows to use "req.user" and applied tsconfig.json.

Path: src/@types/express/index.d.ts

import { User } from '../../model/user/user.interface';

declare global {
    namespace Express {
        interface Request {
            user?: User['employeeId'];
        }
    }
}

tsconfig.json

{
    "compilerOptions": {
        "typeRoots": [
          "./node_modules/@types",
          "./src/@types"
        ],
        "rootDir": ".",
        "module": "CommonJS",
        "strict": true,
        "outDir": "dist",
        "baseUrl": "./src",
        "paths": {
            "*": ["node_modules/@types/*", "src/@types"]
        },
        "esModuleInterop": true
    },
    "include": ["src/**/*.ts"]
}

controller

Path: src/api/posts/controller.ts

export const get = (req: Request, res: Response) => {
  ...
  const { user } = req;
  -> occrud Error
};

What am I missing?

COLEAN
  • 665
  • 2
  • 9
  • 24

2 Answers2

2

The issue is that ts-node is not picking up your type extensions, but tsc is able to. The relevant GitHub Issue has more details but the TL;DR is that you have to put your custom types before the node_modules/@types ie:

"typeRoots": [
  "./src/@types",
  "./node_modules/@types"
]

paths is also not needed, so you can probably remove that (it's wrong anyway).

kierans
  • 2,034
  • 1
  • 16
  • 43
0
{
    "compilerOptions": {
        "rootDir": "./src",
        "module": "CommonJS",
        "strict": true,
        "outDir": "./dist",
        "baseUrl": "./node_modules",
        "paths": {
            "*": ["./@types/*","./*", "../src/@types"]
        },
        "esModuleInterop": false,
        "types": ["node", "express"]
    },
    "include": ["src/**/*.ts"]
}

let's npm -D install @types/node @types/express

now let's create a class controller

import { Request, Response, NextFunction } from "express";


export type EndPointResponse = Promise<Response>;
export class ListController {

    public constructor () {
        this.getAll = this.getAll.bind(this);
        this.getById = this.getById.bind(this);
    }

    public async getAll (req: Request, res: Response, next: NextFunction): EndPointResponse {

    }
    public async getById (req: Request, res: Response, next: NextFunction): EndPointResponse {

}

here you have complete explanation https://medium.com/@enetoOlveda/use-sequelize-and-typescript-like-a-pro-with-out-the-legacy-decorators-fbaabed09472

Ernesto
  • 3,944
  • 1
  • 14
  • 29