Namespace modifications did not successfully compile in Typescript

I am facing an issue with extending the User type in express.js by including an express.d.ts declaration file in my project. Although adding the declaration file removes the error indicators in VS Code, Typescript is failing to compile. I am encountering errors like

TS2339: Property 'id' does not exist on type 'User'
during compilation even though intellisense is able to recognize the declarations.

express.d.ts

import { Channel, User as DbUser } from '../entities'

declare global {
    namespace Express {
        interface Request {
            channel?: Channel
        }

        //User already exists on Request and is of type {}
        interface User extends DbUser {

        }
    }
}

tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "ES2017",
        "pretty": true,
        "strict": true,
        "alwaysStrict": true,
        "noImplicitThis": false,
        "noUnusedLocals": true,
        "strictNullChecks": false,
        "noUnusedParameters": false,
        "noFallthroughCasesInSwitch": true,
        "baseUrl": ".",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "esModuleInterop": true,
        "lib": [ "ESNext" ]
    }
}

package.json

{
    "dependencies": {
        // ...brevity
        "express": "^4.17.1",
        "ts-loader": "^5.4.5",
        "ts-node": "^8.6.2",
        "typescript": "^3.7.5"
    },
    "devDependencies": {
        // ...brevity
        "@types/express": "^4.17.2",
        "@types/express-serve-static-core": "^4.17.2",
    }
} 

compilation error TSError: ⨯ Unable to compile TypeScript: src/middleware/authorize.ts(8,34): error TS2339: Property 'session' does not exist on type 'Request'. src/middleware/authorize.ts(10,35): error TS2339: Property 'badges' does not exist on type 'User'. src/middleware/authorize.ts(25,34): error TS2339: Property 'session' does not exist on type 'Request'. src/middleware/authorize.ts(27,35): error TS2339: Property 'badges' does not exist on type 'User'. src/middleware/authorize.ts(42,34): error TS2339: Property 'session' does not exist on type 'Request'. src/middleware/authorize.ts(44,35): error TS2339: Property 'badges' does not exist on type 'User'.

Answer №1

👨‍🏫 Give it a shot: Copy and paste the following code snippet to define your custom express interface: 👇

import { Channel, User as DbUser } from '../entities'

declare module 'express' {
  interface Request {
    channel?: Channel
  }

  interface User extends DbUser {
  }
}

I tested out the above code myself and everything is working smoothly.

Hopefully this solution proves helpful to 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

Debugging Node.js Routes in Visual Studio Code: A Step-by-Step Guide

My application is structured as follows: server.js router routes emails.js index.js In my index.js file, I define the route like this: module.exports = function (app) { app.use('/emails', require('./routes/emails& ...

Creating blank entities with app.post using AngularJS and mongoose in a node.js environment

My issue seems to be with my REST API as it is posting empty objects. The value I am retrieving from req.body.name appears correctly when I log it using console.log(req.body.name);. POST: { name: 'typing any name', status: null } typing any na ...

Arranging a collection of objects in alphabetical order

My current challenge involves sorting an array of objects alphabetically, and to simplify things, I have provided the example below. In my TypeScript code, I utilize splice to add and remove items from the object array. Array cars = [{ id: 1, ...

Vue.js - A dynamic parent component generates content based on data passed from a renderless child component

I am currently working on developing a system for generating buttons using vue 3 and vue-class-component. The main goal is to create a flexible button generation process, where the number of buttons generated can vary (it could be just one or multiple). Us ...

Can you explain the significance of the "@" symbol in the `import from '@/some/path'` statement?

When I use IntelliJ IDEA to develop a web application in TypeScript, the autocomplete feature suggests imports from other files within my project like this: import {Symbol} from '@/components/Symbol'; I am curious about the significance of the @ ...

Using react-router to fetch data from the server side

I have successfully implemented React-router server-side rendering in my express app using the following code snippet: app.use((req, res) => { match({ routes, location: req.url }, (error, redirectLocation, renderProps) => { console.log(renderProps) ...

Tips for transferring the button ID value to a GET request?

I recently developed a Node.js application that interacts with a database containing student information and their current marks. Utilizing MongoDB, I retrieve the data and present it in a table within an .ejs file. index.js router.get("/dashboard", funct ...

Having trouble accessing property '0' of undefined in angular

Below is the code I am currently working on. My goal is to enable editing of the table upon click, but I encountered the error mentioned below. Could someone kindly explain why this is happening and suggest a workaround? <tbody> <tr *ngFor="l ...

Tips for eliminating unnecessary module js calls in Angular 9

https://i.sstatic.net/3R7sr.png Utilizing a lazy loading module has been efficient, but encountering challenges with certain modules like all-access-pass and page not found as shown in the image above. Is there a way to effectively remove unused module J ...

Is there a way I can restrict the amount of admin roles to only one within my schema?

data-schema.js: const userInfoSchema = new mongoose.Schema({ accessLevel: { type: String, enum: ["limited", "user", "admin"], default: "limited", }, }) Is it possible to enforce a rule where only one admin can have full access at any given ...

Tips for specifying a clear type in TypeGraphQL when dealing with key-value pair objects

In my efforts to define explicit types in type-graphql for key-value pairs, I am encountering an issue. I have declared the key-value pair using [key: string]: string, indicating that the keys can be of any string type and the values must be strings. This ...

New patch request received in Google Sheets, replacing the existing post request

I am transferring 12 cell values from a Google Sheet to a MongoDB database. The purpose behind this action is to merge the 12 cells, perform certain data transformations, and display the output on a frontend interface later on. Moreover, I'm faced wit ...

Can you provide guidance on how to specifically specify the type for the generics in this TypeScript function?

I've been diving into TypeScript and experimenting with mapped types to create a function that restricts users from extracting values off an object unless the keys exist. Take a look at the code below: const obj = { a: 1, b: 2, c: 3 } fun ...

Socket.emit allows for the transmission of various data points

Can someone help me with an issue I'm facing regarding socket.emit inside socket.on concatenating the same value after every emitting? Below is the code snippet on the server-side: io.on('connection', function(socket){ let balance = 6000; ...

SequelizeEagerLoadingError: There is no association between the model and the otherModel

I've come across this issue several times on various forums but haven't been able to resolve it yet. My setup involves Express and PostgreSQL with Sequelize ORM. The problem lies in the one-to-one relationship between two models: Campus and Acad ...

Guidelines for creating a dynamic filter in Prisma js

I am looking to create a dynamic filter based on user input from the frontend. On mapping the data, I found that the object results appear like this: { id: '2', name: 'yuhu' } The keys 'id' and 'name' need to be dyn ...

Receiving an error when triggering an onclick event for a checkbox in TypeScript

I am creating checkboxes within a table using TypeScript with the following code: generateTable(): void { var table = document.getElementById("table1") as HTMLTableElement; if (table.childElementCount == 2) { for (var x = 0; x < 2; x++) ...

The body of the POST request appears to be void of any

Whenever I make a request using curl or hurl, an issue arises. Despite req.headers['content-length'] showing the correct length and req.headers['content-type'] being accurate, req.body returns as {}. Below is the Hurl test: POST http:/ ...

What causes TypeScript to narrow the type when a return statement is present, but not when it is absent?

I am facing an issue with this script: type Input = string function util(input: Input) { return input } function main(input: Input | null) { const isNull = input === null if (isNull) { return 'empty string' } inpu ...

Having difficulty launching a TypeScript Node.js application using ts-node and pm2

I have a node app built with TypeScript and it works fine with nodemon, but when I try to move it to the server using PM2, I encounter errors. I've searched GitHub and StackOverflow for solutions, but nothing has worked for me so far. Any help would b ...