- Always define explicit types for all props passed to custom or Shadcn/UI components. Utilize Zod schemas to validate complex prop structures, especially for data passed from server components or API routes. This ensures type safety at runtime and during development.
Example:
```typescript
// components/UserCard.tsx
import { z } from 'zod';
import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; // Assuming Shadcn/UI path
const userCardPropsSchema = z.object({
userId: z.string().uuid(),
name: z.string().min(1),
email: z.string().email().optional(),
registrationDate: z.date(),
});
type UserCardProps = z.infer<typeof userCardPropsSchema>;
export const UserCard = ({ userId, name, email, registrationDate }: UserCardProps) => {
// Validate props at runtime (optional, primarily for data from external sources)
try {
userCardPropsSchema.parse({ userId, name, email, registrationDate });
} catch (error) {
console.error("Invalid UserCard props:", error);
return <p>Error loading user data.</p>;
}
return (
<Card>
<CardHeader>
<CardTitle>{name}</CardTitle>
{email && <CardDescription>{email}</CardDescription>}
</CardHeader>
<CardContent>
<p>User ID: {userId}</p>
<p>Registered: {registrationDate.toLocaleDateString()}</p>
</CardContent>
</Card>
);
};
```
rationale: Enhances code reliability and maintainability by catching type errors early and ensuring components receive the data they expect.