Typescript fails to detect type files when attempting to extend the `Request` object in Express, allowing for the addition of custom properties to be used in middleware functions

In my current typescript project utilizing express for backend API calls, the issue arises when attempting to assign custom properties. Typescript throws an error indicating that these properties do not exist.

To address this, I created a custom types subdirectory within the project structure. This subdirectory is intended to manage additional attributes and custom types that might be added later in the project's lifecycle. The project setup looks like this:

src
│   index.ts
│   
├───config
│       database.ts
│       
├───routes
│       login.ts
│       router.ts
│       signup.ts
│       upload.ts
│       
├───types
│       express.d.ts
│
└───utils
        auth.ts

All other configuration files are located at the top level (such as package.json or package-lock.json). To incorporate the 'types' subdirectory, modifications were made to the tsconfig.json file with the following settings:

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "typeRoots": [
      "./node_modules/@types",
      "./src/types"
    ]
  },
  "exclude": [
    "node_modules",
    "dist"
  ]
}

The type file includes the following content:

// express.d.ts
import { Request } from 'express';

interface User {
    id: number,
    username: string,
    token_type: string
}

declare global {
    namespace Express {
        interface Request {
            files?: any,
            user: User
        }
    }
}

Despite these settings, an error occurs when trying to access or modify the newly assigned attributes, indicating that they do not exist:

C:\Users\Me\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:859
    return new TSError(diagnosticText, diagnosticCodes, diagnostics);
           ^
TSError: ⨯ Unable to compile TypeScript:
src/routes/upload.ts:29:14 - error TS2339: Property 'files' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

29     if (!req.files || Object.keys(req.files).length === 0) {
                ~~~~~
src/routes/upload.ts:29:39 - error TS2339: Property 'files' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

29     if (!req.files || Object.keys(req.files).length === 0) {
                                         ~~~~~
src/routes/upload.ts:32:22 - error TS2339: Property 'files' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

32     const file = req.files.Filename
                        ~~~~~
src/routes/upload.ts:37:13 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

37         req.user!.id,
               ~~~~

    at createTSError (C:\Users\Me\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:859:12)
    at reportTSError (C:\Users\Me\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:863:19)
    at getOutput (C:\Users\Me\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:1077:36)
    at Object.compile (C:\Users\Me\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:1433:41)
    at Module.m._compile (C:\Users\Me\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:1617:30)
    at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
    at Object.require.extensions.<computed> [as .ts] (C:\Users\Me\AppData\Roaming\npm\node_modules\ts-node\src\index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Function.Module._load (node:internal/modules/cjs/loader:938:12)
    at Module.require (node:internal/modules/cjs/loader:1115:19) {
  diagnosticCodes: [ 2339, 2339, 2339, 2339 ]
}

I have searched online for solutions without success. Any assistance would be greatly appreciated! :D

Answer №1

{
  "include": ["test/**/*", "src/**/*"],
  "compilerOptions": {
    "target": "es2016",
    ...
  },
  "files": [
    ".//src/types/express.d.ts"
  ]
}

The key thing is to insert the "files" section into your tsconfig.json

  "files": [
    ".//src/types/express.d.ts"
  ]

This addition should definitely assist you

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to setting a constant in express js

I am looking to define a constant that can be used throughout my application. For instance: var config = require('../../config.js'); I would like it to be: var config = require(baseUrl + '/config.js'); where baseUrl = host + port ...

Encrypting user passwords using bcrypt in the "pre" format

I am attempting to securely store a hashed password in a MongoDB database using bcrypt encryption. Below is the form I am working with: <form action="/register" method="POST"> <label for="firstname">Firstname</l ...

Node JS becomes unresponsive when encountering the Error: ENOENT

My web application runs on node.js (version 10.28) and express (version 3.4.7). Here is a snippet of the server.js code: var express = require('express'), config = require('./services/resource/config.js'), routeprocess = require(' ...

``Is there a specific scenario where it is recommended to use cookie-parser alongside express-session

Many ExpressJs tutorials suggest using cookie-parser in conjunction with express-session. If I can access session data using req.session.name without it, when would be a good reason (or advantage) to use cookie-parser? ...

Seeking a solution for the insecure http protocol being blocked by the Flutter platform?

I've been struggling to retrieve data from my custom REST API and keep encountering an error. I even followed the official migration guide from Google. import 'package:flutter/material.dart'; import 'dart:convert'; import 'pac ...

Exploring the method of iteratively pairing Typescript test files with a NodeJS native testrunner

A new native test runner was recently introduced in NodeJS. I have managed to run typescript tests using ts-node or tsx node --loader ts-node/esm --test **/*.test.ts node --loader tsx --test **/*.test.ts However, a significant issue I encountered is tha ...

What is the method for obtaining class constructor argument types in the form of an object?

Let's consider an example where we have a class called Summator: export default class Summator { constructor(private readonly firstArgument: number, private readonly secondArgument: number) {} get sum() { return this.firstArgument + this.s ...

Imitation Google Maps object featuring TypeScript definitions

My Angular component relies on the google.maps.Map class. Here's what it looks like: export class MapViewComponent implements OnInit { @Input() public mapOptions: google.maps.MapOptions; public map: google.maps.Map; @ViewChild(" ...

The type Observable<any> cannot be assigned to Observable<any> type

I am currently working with angular 5 and ionic 3. I have defined an interface: export interface IAny { getDataSource: Observable<any>; } Components that implement this interface must have the following method: getDataSource () { return ...

Issue with Docusign template text tabs not populating

I am currently using my production account on Docusign to facilitate document signing for users. I am facing an issue with adding data to textTabs that I create through the Docusign dashboard. Even though I add a text box named "nbShares," the code provide ...

Setting up VSCode to run various tasks

My TypeScript project in Visual Studio Code has a specific task outlined as follows: { "version": "0.1.0", // The command is tsc. "command": "tsc", // Show the output window only if unrecognized errors occur. "showOutput": "silent", // Und ...

Tips for successfully mocking axios.get in Jest and passing AxiosPromise type value

I attempted to simulate the axios.get() function using the code below, however TypeScript is returning an error stating "argument of type '{ data: expectedResult }' is not assignable to parameter of type 'AxiosPromise<{}>'". Can ...

Express.js failing to send back a response

After attempting this process numerous times, I am puzzled by the behavior of my code in this particular scenario. The situation involves sending login credentials from a webpage to an express server: async function request(url, data) { data = JSON.strin ...

Error: Trying to access the 'keyboard' property of an undefined object

I am encountering an error message 'Cannot read property 'keyboard' of undefined' and I'm not sure how to fix it. I just want to check if the keyboard is visible on the screen, but this specific line of code seems to be causing the ...

My authentication process involves utilizing auth0 for verifying users, coupled with an API designed for creating, reading, updating, and deleting posts which include fields for titles, images, and descriptions. What steps should be

I am currently in the process of developing a react application and have implemented auth0 for user authentication. Prior to integrating auth0, I was sending CRUD requests to my API to create posts without any user authentication in place. Now that I have ...

Payment Unsuccessful with Apple Pay through Stripe

After successfully setting up the Stripe "Payment Request Button" for Apple Pay on my website and verifying its functionality within the Stripe logs, I encountered an issue. Each time I attempted to complete a test payment, Apple Pay returned an error mess ...

NodeJS Error: JSON cannot handle circular structure conversion

My HTTP API built using Express in Node.js for CRUD operations is mostly functional. However, I encountered an error when making a GET request: TypeError: Converting circular structure to JSON. Fortunately, other HTTP methods like POST and DELETE are work ...

Error: Invalid JSON Web Token structure

I am working on creating a middleware to authenticate users using JWT and cookies. After decrypting the cookie that was encrypted during the login process, I attempted to verify it using jwt.verify(). However, I encountered an error message: JsonWebTokenEr ...

NodeJS routing can be disrupted by URL parameters causing issues

I've encountered an issue while trying to use express to serve my index.html, its dependencies, and handle URL parameters. Adding a URL param seems to disrupt the pathing. My nodeJS webapp has a simple folder structure: |- server.js (contains nodeJS ...

Exploring the world of local passport strategies with the power of cURL

Exploring my node.js + express + passport.js testing application (RESTful) using CURL. Here's my code: var express = require('express'); var routes = require('./routes'); var http = require('http'); var path = require(&a ...