Typescript errors in NextJS learning course
Unanswered
American Fuzzy Lop posted this in #help-forum
American Fuzzy LopOP
Guys, I following NextJS tutorial https://nextjs.org/learn/dashboard-app/improving-accessibility#server-side-validation but has problems with Typescript. In the snippet below
State type is unresolved. The same with validatedFields.error, TS says Property 'error' does not exist on type 'SafeParseSuccess<{ customerId?: string; amount?: number; status?: "pending" | "paid"; }>'. I don't understand why only SafeParseSuccess is considered in typecheck while it's should be union of SafeParseSuccess and SafeParseError. The TS errors are shown in Visual Studio Code.'use server';
import { z } from 'zod';
import prisma from '@/app/lib/db';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
const FormSchema = z.object({
id: z.number(),
customerId: z.string({
invalid_type_error: 'Please select a customer.',
}),
amount: z.coerce
.number()
.gt(0, { message: 'Please enter an amount greater than $0.' }),
status: z.enum(['pending', 'paid'], {
invalid_type_error: 'Please select an invoice status.',
}),
date: z.string(),
});
const CreateInvoice = FormSchema.omit({ id: true, date: true });
export async function createInvoice(prevState: State, formData: FormData) {
const validatedFields = CreateInvoice.safeParse({
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
});
console.log('validatedFields', validatedFields);
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to Create Invoice.',
};
}
...1 Reply
American Fuzzy LopOP
I found that changing conditional to code below resolves issue with
error prop not exists. Other issues still related. The original version works when strictNullChecks: true https://www.typescriptlang.org/tsconfig/strictNullChecks.html. if (validatedFields.success == false) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: 'Missing Fields. Failed to Create Invoice.',
};
}