The type 'Application Record' is lacking these specific properties: string, any init, defaultConfiguration, and engine

I am encountering an error while running my TypeScript project:

yarn build
yarn run v1.22.22
$ tsc && tsc-alias
src/index.ts:22:23 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>' is not assignable to parameter of type 'Application<Record<string, any>>'.
      Type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => Promise<...>' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 63 more.

22 app.get('/users/:id', getUserById);
                         ~~~~~~~~~~~

  node_modules/@types/express-serve-static-core/index.d.ts:164:5
    164     (path: PathParams, subApplication: Application): T;
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The last overload is declared here.

src/index.ts:23:20 - error TS2769: No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request, res: Response, next: NextFunction) => Promise<Response<any, Record<string, any>> | undefined>' is not assignable 
to parameter of type 'Application<Record<string, any>>'.
      Type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => 
Promise<...>' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 63 more. 

23 app.post('/users', createUser)
                      ~~~~~~~~~~

  node_modules/@types/express-serve-static-core/index.d.ts:164:5
    164     (path: PathParams, subApplication: Application): T;
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The last overload is declared here.


Found 2 errors in the same file, starting at: src/index.ts:22

error Command failed with exit code 2.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Code

index.ts (main file)

import express from 'express';
import dotenv from 'dotenv';
import cors from 'cors';
import morgan from 'morgan';
import { createInventory } from './controllers';

dotenv.config();

> //express app
const app = express();
app.use(express.json());
app.use(cors());
app.use(morgan('dev'));

app.get('/health', (_req, res) => {
res.status(200).json({ health: 'UP' })
> })

> //Routes
app.post('/iventories', createInventory);

controllers/index.ts

export { default as createInventory } from './createInventory';

controllers/createInventory.ts

import { Request, Response, NextFunction } from "express";
import prisma from "@/prisma";
import { InventoryCreateDTOSchema } from "@/schemas";

const createInventory = async (req: Request, res: Response, next: NextFunction) => {
    try {

        const parsedBody = InventoryCreateDTOSchema.safeParse(req.body)
        
        const inventory = await prisma.inventory.create({
            data: {
                ...parsedBody.data,
                histories: {
                    create: {
                        quantityChanged: parsedBody.data.quantity,
                    }
                }
            },
            select: {
                id: true,
                quantity: true,
            }
        });
        return res.status(201).json(inventory);
    } catch (error) {
        next(error);
    }
};

export default createInventory;

createUser

import { Request, Response, NextFunction } from "express";
import { UserCreateSchema } from '@/schemas'
import prisma from "@/prisma";

const createUser = async (req: Request, res: Response, next: NextFunction) => {

    try {

        const parsedBody = UserCreateSchema.safeParse(req.body)
        if (!parsedBody.success) {
            return res.status(400).json({ error: parsedBody.error.errors })
        }


        //create new user
        const user = await prisma.user.create({
            data: parsedBody.data,
        })


        return res.status(201).json(user);
    } catch (error) {
        //next(error);
    }
};

export default createUser;

getUserById

import { Request, Response, NextFunction } from "express";
import { UserCreateSchema } from '@/schemas'
import prisma from "@/prisma";
import { User } from "@prisma/client";

const getUserById = async (req: Request, res: Response, next: NextFunction) => {
    try {

        const { id } = req.params;
        const field = req.query.field as string;
        let user: User | null = null;

        if (field == 'authUserId') {
            user = await prisma.user.findUnique({ where: { authUserId: id } })
        } else {
            user = await prisma.user.findUnique({ where: { id } })
        }

        return res.json(user);
    } catch (error) {
        next(error);
    }
};

export default getUserById;

tsconfig.json

    {
        "compileOnSave": false,
        "compilerOptions": {
            "target": "ESNext",
            "lib": ["ES6"],
            "allowJs": true,
            "module": "CommonJS",
            "rootDir": ".",
            "outDir": "./dist",
            "esModuleInterop": true,
            "strict": true,
            "skipLibCheck": true,
            "forceConsistentCasingInFileNames": true,
            "moduleResolution": "node",
            "resolveJsonModule": true,
            "allowSyntheticDefaultImports": true,
            "typeRoots": ["./src/types", "./node_modules/@types"],
            "sourceMap": true,
            "types": ["node", "express"],
            "noImplicitAny": false,
            "baseUrl": "./src",
            "paths": {
                "@/*": ["*"],
            }
        },
        "include": ["src/**/*"],
        "exclude": ["node_modules"]
    }

I have tried various solutions like reinstalling TypeScript, upgrading Node.js, and rewriting the code but the error persists across different routes.

Answer №1

Check out this source code snippet

import { Request, Response, NextFunction } from 'express'
import { UserCreateSchema } from '@/schemas'
import prisma from '@/prisma'

const addUser = async (req, res, next) => {
    try {

        const requestBody = UserCreateSchema.safeParse(req.body)
        if (!requestBody.success) {
            return res.status(400).json({ message: requestBody.error.errors })
        }

        //add new user
        const user = await prisma.user.create({
            data: requestBody.data,
        });

        return res.status(201).json(user);
    } catch (error) {
        next(error);
    }
};

export default addUser;

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

Using the multer package in Node Express to upload an image through an API

This question has been asked previously. However, since I didn't find a solution to my issue, I am posting it again. I am currently attempting to upload an image for a property using the multer package to handle form-data in order to store additional ...

Similar to Java method references, TypeScript also provides a way to reference functions

Although I am familiar with Java, TypeScript is fairly new to me. In Java, lambda expressions (->) or method references (::) are commonly used to satisfy functional interfaces. It seems like lambda expressions function similarly in both languages (plea ...

Is there a way to prevent Express from automatically converting the '+' character in query strings to spaces when making a GET request?

During a GET request, I am including specific parameters in the query string such as HOST?email=john**+[email protected]. However, when trying to retrieve these values in my Node Express server using req.query.email, the value received is 'john [ ...

Encountering an issue when trying to access a class's member variable within the "then" function of

Trying to develop a simple contact list app using Angular 4 and facing an issue with the delete functionality. When attempting to delete a contact, the contacts variable inside the 'then' function is returning undefined. The main problem lies w ...

Exploring cross-site session management using a NodeJS/Passport/Express backend integrated with a Polymer frontend

Currently, I have a node/express/passport backend running on port 3001 that I am accessing directly from the browser for authentication purposes. It successfully authenticates and manages access to protected URLs. The frontend is built using Polymer and is ...

MongoDB ratings are failing to update as anticipated

I'm currently working on incorporating a rating system similar to upvotes and downvotes. Users have the ability to vote on a lesson only once. They can change their votes between up and down. If they vote the same as their previous vote, it cancels ou ...

I am confused as to why I am encountering an issue with req.file being "undefined" when attempting to upload a file using multer

Trying to implement a feature where users can upload files using a form, but encountering issues with multer in the controller file. When using upload.single('foobar'), the image is returning as "undefined", causing errors in the application. Spe ...

Develop a web server by using the Node.js MVC architecture

I am currently in the process of developing a web server, and have decided to utilize the MVC model. I have incorporated routes within the server, but am encountering issues with data retrieval. When logging the data to the console, it displays all the inf ...

Angular's GET HTTP request has resulted in a 500 error message, specifically the Internal Server Error

Attempting to send a GET request to the server where only authenticated users can access a specific route ("/user") after logging in. However, even after a successful login, users are unable to gain access to the "/user" route. A middleware function named ...

Error TS2604: Upon importing the 'material-ui' button from one package into another

Our team is in the process of implementing a new front-end for our application by transitioning from standard react to typescript. As someone who is relatively new to development, I have been struggling with a particular issue for several days now. The set ...

Guide on integrating TypeScript with the Esri Leaflet JavaScript Plugin

I'm working on an Aurelia project in TypeScript that incorporates Leaflet for mapping. So far, I've been able to use typings for Leaflet itself, but the esri-leaflet plugin is only available in JavaScript. How can I import and utilize this JavaSc ...

The res.json method does not include headers for the HTTP status code

I need help adding headers to the json object I am sending. Despite my attempts to use the setHeaders method, I keep encountering a Can't set headers after they are sent. error. In a helpful response on Stack Overflow, it is mentioned that Since ...

Unable to add a new entry to the MongoDB database

I'm currently working on a project in MEAN STACK and I have the requirement to import data for countries, states, and cities. While I've been able to successfully import countries and states from JSON files, I'm facing an issue with importin ...

What is the procedure for incorporating nameless methods into TypeScript interfaces?

While working on a project involving graph visualization, I came across the following interface within the d3.js typings (original source can be found here): export interface Force<NodeDatum extends SimulationNodeDatum, LinkDatum extends SimulationLink ...

IntelliSense for TypeScript Variable Names in Intellij

When declaring a variable or field in Java, it is common practice to specify the type. For example: public SomeDataType someDataType = new SomeDataType(123) As you begin typing Som.., IntelliJ's autocomplete feature will likely suggest SomeDataTyp ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Using the Ngclass function with a pair of objects

Can you include 2 objects in an ngclass function like this? <div class="progress-bar"[ngClass]="getProgressValues(obj.val1,obj.val2)"> </div> I am encountering a JSON error. SyntaxError: JSON.parse: bad control character in string literal at l ...

Console displays an unusual error when submitting the form

I am currently developing a small ToDo application with Angular on the front-end and Node.js/Express/Mongo on the back-end. Upon submitting the Login form, it triggers the login API but I am seeing an unusual output in the console: OPTIONS http://local ...

Implement ExpressTS on vercel platform

I have recently developed an Express TypeScript project on GitHub and now I am attempting to deploy it to Vercel. The folder structure of the project is as follows, with 'dist' containing app.js and 'src' containing app.ts. dist dto mi ...

Unable to invoke extension method on parent class in TypeScript

Wondering about classes and extensions in TypeScript? Let's take a look at an example: We have a base class called Report, with another class named Datasheet that extends from Report. An extension has been added to the Report class, and the goal is ...