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",
});
}
In the "GET" part above, there is an error reported by Typescript for "auth". The error message states -- 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'
I cannot figure out what mistake I've made. Everything seems fine and works as intended when ignoring the Typescript error.
There's something missing that I can't seem to resolve.