Error: Type 'FormDataEntryValue' is not assignable to type 'string'. Type 'File' is not assignable
Answered
Jenn posted this in #help-forum
JennOP
I have this data that I get from the
Error:
Error occurs on the
formData
and I want it to pass for the function for sending an email. Error:
` Type 'FormDataEntryValue' is not assignable to type 'string | null'.ts(2322)
definitions.ts(119, 3): The expected type comes from property 'lastName' which is declared here on type 'InvoiceEmailData'
(property) lastName: string | null
No quick fixes available
Error occurs on the
InvoiceEmailData
for firstName
, lastName
, and remarks
. 'use server'
try{
const firstName = formData.get('firstName')
const lastName = formData.get('lastName')
const remarks = formData.get('remarks')
//rest of the codes...
//sending an email
try{
const emailData: InvoiceEmailData = {
firstName: firstName || "",
lastName: lastName || "",
order_id: order_id || "",
cart: cart,
total: total,
remarks
};
const res = await sendMailFunction({
to: "",
name: `${emailData.firstName} ${emailData.lastName}`,
subject: `New Order Placed ${emailData.order_id}`,
body: generateInvoiceEmailBody(emailData),
});
Answered by joulev
it is
recommended to use [
assertion is not a good idea imo because you cant guarantee only your frontend triggers this action. an attacker could send a bad form with
string | File | null
. so you have to check typeof value
if (typeof firstName !== "string")
throw new Error("firstName is not a string!");
recommended to use [
zod-form-data
](https://www.npmjs.com/package/zod-form-data) for this which will handle file/string/null validation for you and moreassertion is not a good idea imo because you cant guarantee only your frontend triggers this action. an attacker could send a bad form with
firstName
as a file and that will blow your backend up if you dont handle it properly7 Replies
const firstName = formData.get("firstName") as string
const lastName = formData.get('lastName') as string
const remarks = formData.get('remarks') as string
it should be
string | null
tho... https://developer.mozilla.org/en-US/docs/Web/API/FormData/get#return_value (idk tho)it is
recommended to use [
assertion is not a good idea imo because you cant guarantee only your frontend triggers this action. an attacker could send a bad form with
string | File | null
. so you have to check typeof value
if (typeof firstName !== "string")
throw new Error("firstName is not a string!");
recommended to use [
zod-form-data
](https://www.npmjs.com/package/zod-form-data) for this which will handle file/string/null validation for you and moreassertion is not a good idea imo because you cant guarantee only your frontend triggers this action. an attacker could send a bad form with
firstName
as a file and that will blow your backend up if you dont handle it properlyAnswer
ohh i should have actually checked the types
yeah that +1 to that recommendation
yeah I use zod usually 😆
JennOP
Thanks, both solutions have worked