You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.tsx 735B

123456789101112131415161718192021222324
  1. 'use client'
  2. import React from 'react'
  3. import type { ZodSchema } from 'zod'
  4. function withValidation<T extends Record<string, unknown>, K extends keyof T>(
  5. WrappedComponent: React.ComponentType<T>,
  6. schema: ZodSchema<Pick<T, K>>,
  7. ) {
  8. return function EnsuredComponent(props: T) {
  9. const partialProps = Object.fromEntries(
  10. Object.entries(props).filter(([key]) => key in (schema._def as any).shape),
  11. ) as Pick<T, K>
  12. const checkRes = schema.safeParse(partialProps)
  13. if (!checkRes.success) {
  14. console.error(checkRes.error)
  15. // Maybe there is a better way to handle this, like error logic placeholder
  16. return null
  17. }
  18. return <WrappedComponent {...props} />
  19. }
  20. }
  21. export default withValidation