Luca Del Puppo - Senior Software Developer
Luca Del Puppo
Love sport: running, hiking
Love animals
Image by catalyststuff on Freepik
export interface CustomerModel {
id: number;
name: string;
email: string;
phone: string;
};
export type CustomerModel = {
id: number;
name: string;
email: string;
phone: string;
};
Until
Hey, I'm a backend dev
and now I'll change the API
Image by catalyststuff on Freepik
NaN
Unexpected string
NaN
Unexpected string
Image by catalyststuff on Freepik
Image by catalyststuff on Freepik
import { z } from 'zod';
export const CustomerSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string(),
phone: z.string(),
});
import { TypeOf } from 'zod';
export type CustomerModel = TypeOf<typeof CustomerSchema>;
const customer = CustomerSchema.parse({
id: 1,
name: 'John Doe',
email: 'email@email.com',
phone: '123456789',
});
Validation
Layer
HTTP
socket
import { useParams } from "react-router-dom";
function OrderPage() {
const { id } = useParams()
// const id: string | undefined
...
}
const OrderParamsSchema = z.object({
id: z.coerce.number(),
})
function OrderPage() {
const { id } = useParamsTypeSafe(OrderParamsSchema)
// const id: number
...
}
import { useParams } from 'react-router-dom';
import { ZodType, ZodTypeDef, z } from 'zod';
const useParamsTypeSafe = <Schema extends ZodType<Output, Def, Input>,
Output,
Def extends ZodTypeDef,
Input
>(schema: Schema): z.infer<Schema> => {
const params = useParams();
return schema.parse(params)
};
export default useParamsTypeSafe
Image by catalyststuff on Freepik
import { ZodTypeAny, z } from 'zod';
import { validate } from '../zod/validation';
const withZodValidation =
<Schema extends ZodTypeAny, P extends z.infer<Schema>>(schema: Schema) =>
(Component: React.ComponentType<P>): React.FC<P> =>
function ComponentWithValidation(props: P) {
const realProps = schema.parse(props)
return <Component {...realProps} />;
};
export default withZodValidation
const OrderPropsSchema = z.object({
order: OrderSchema,
onView: z.function().args(OrderSchema).returns(z.void()),
onDelete: z.function().args(OrderSchema).returns(z.void()),
})
function Order(
{ order, onView, onDelete }: z.infer<typeof OrderPropsSchema>
): ReactElement | null {
....
}
export default withZodValidation(OrderPropsSchema)(Order)
Image by catalyststuff on Freepik
Image by catalyststuff on Freepik
@puppo92
Luca Del Puppo
Puppo_92
@puppo