Promise 缺少类型“应用程序记录字符串、任何 init、defaultConfiguration、引擎”中的以下属性

问题描述 投票:0回答:1

我正在运行 ts 项目,但出现此错误

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.

代码

index.ts(主文件)

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);

控制器/index.ts

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

控制器/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;

创建用户

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;

通过Id获取用户

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"]
    }

我为其他路线编写代码,但错误是相同的。好几次我安装了ts并升级了节点并编写了几次代码但错误都是相同的,

typescript express cors dotenv
1个回答
0
投票

这是源代码

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 })
        }

        const existingUser = await prisma.user.findUnique({
            where: { authUserId: parsedBody.data.authUserId },
        });

        if (existingUser) {
            return res.status(400).json({ message: 'User already exists' });
        }

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

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

export default createUser;
© www.soinside.com 2019 - 2024. All rights reserved.