如何解决Next.js路由中TypeScript报告的auth类型不兼容错误?
Next.js API路由TypeScript类型错误修复
我在Next.js的API路由中编写了如下代码:
import type { NextApiRequest, NextApiResponse } from "next"; import db from "../../app/libs/dbConn"; interface DataProps { auth: [ { name?: string; email?: string; passwordHash?: string; } ]; status: number; message: string; } export default async function handler( req: NextApiRequest, res: NextApiResponse<DataProps> ) { if (req.method === "POST") { const data = { name: "Gary", email: `gary@${Math.floor(Math.random() * 9999999)}.subdomain.com`, passwordHash: "-", }; const user = await db.user.create({ data }); return res .status(200) .json({ auth: [data], status: 201, message: "created user" }); } if (req.method === "GET") { const allUsers = await db.user.findMany(); const users = allUsers.map((user) => { return { name: user.name || "", email: user.email || "", passwordHash: "" || "", }; }); return res .status(200) .json({ auth: users, status: 200, message: "success" }); } return res.status(404).json({ auth: [{}], status: 405, message: "http verb not supported", }); }
在GET请求处理部分,TypeScript报出如下错误:
Type '{ name: string; email: string; passwordHash: string; }[]' is not assignable to type '[{ name?: string | undefined; email?: string | undefined; passwordHash?: string | undefined; }]'.
Target requires 1 element(s) but source may have fewer.ts(2322)
user.ts(6, 3): The expected type comes from property 'auth' which is declared here on type 'DataProps'
错误原因
DataProps接口中auth被定义为固定长度为1的元组类型(直接用方括号包裹对象类型),但GET请求返回的users是长度可变的普通数组,两者类型不兼容,导致TypeScript报错。
修复方案
修改DataProps接口,将auth的类型从元组改为普通数组:
interface DataProps { auth: { name?: string; email?: string; passwordHash?: string; }[]; // 改为数组类型 status: number; message: string; }
修改后,POST返回的单用户数组、GET返回的多用户数组都能匹配类型要求,TypeScript错误即可消除。
内容的提问来源于stack exchange,提问作者Gary
相关产品推荐
相关产品推荐

