typescriptexpresscorsdotenv

Promise is missing the following properties from type 'Application Record string, any init, defaultConfiguration, engine


I am running ts project, but getting this error

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 write code for other routes but the error is the same. Several time I installed the ts and upgrade the node and write code several time but error is the same,


Solution

  • Here is the source code

    import { Request, Response, NextFunction } from 'express'
    import { UserCreateSchema } from '@/schemas'
    import prisma from '@/prisma'
    
    const createUser  = async (req, res, next) => {
        try {
    
            const parsedBody = UserCreateSchema.safeParse(req.body)
            if (!parsedBody.success) {
                return res.status(400).json({ message: 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;