Skip to content

Checked branded types #18

@muradm

Description

@muradm
import { type Lens, useLens } from '@hookform/lenses'
import { zodResolver } from '@hookform/resolvers/zod'
import { useForm } from 'react-hook-form'
import { z } from 'zod'

const EmailAddressS = z.string().min(1).email().brand('EmailAddress')
type EmailAddress = z.infer<typeof EmailAddressS>

const FormSchema = z.object({ email: EmailAddressS })

type FormValue = z.infer<typeof FormSchema>

const Child = ({ lens }: { lens: Lens<FormValue> }) => <></>

function Parent() {
  const { control } = useForm({ resolver: zodResolver(FormSchema) })

  const lens = useLens({ control })

  /*
  Here cannot pass lens as type info is reduced to plain string in useLens().
  Probably "brand" should be opaque/unchecked.
  ....
  Types of property 'email' are incompatible.
    Type 'string | undefined' is not comparable to type 'string & BRAND<"EmailAddress">'.
      Type 'string' is not comparable to type 'string & BRAND<"EmailAddress">'.
        Type 'string' is not comparable to type 'BRAND<"EmailAddress">'.
  */
  return <Child lens={lens} />
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions