Erro de Sobrecarga em TypeScript ao Utilizar React Hook Form em Componente React

Dúvida sobre Erro de Sobrecarga em TypeScript

Estou desenvolvendo um componente React que utiliza TypeScript e React Hook Form. No entanto, ao tentar utilizar o componente, estou enfrentando um erro relacionado a sobrecarga de funções em TypeScript. Vou explicar detalhadamente cada parte do código e do erro.

Código do Componente

import { UseFormReturn } from "react-hook-form";
import { FormItem } from "../ui/form";
import { Label } from "../ui/label";
import { removeNonNumericChars } from "@/lib/utils/remove-non-numeric-chars.util";
import { MaskedInput } from "../ui/input";

interface PhoneInputFormFields {
    countryCode: string;
    areaCode: string;
    number: string;
} 

interface PhoneInputProps<T extends PhoneInputFormFields> {
    form: UseFormReturn<T, any, T>;
}

export function PhoneInput<T extends PhoneInputFormFields>({ form }: PhoneInputProps<T>) {
    return (
        <div className="grid gap-4 sm:grid-cols-3">
            {/* Campo para o código do país */}
            <FormItem>
                <Label htmlFor="countryCode">Código do país</Label>
                <MaskedInput
                    mask="+99"
                    id="countryCode"
                    placeholder="+55"
                    autoCapitalize="none"
                    autoComplete="tel-country-code"
                    autoCorrect="off"
                    value={form.watch("countryCode")}
                    onInput={(event) => {
                        form.setValue(
                            "countryCode",
                            removeNonNumericChars(event.currentTarget.value)
                        );
                    }}
                />
                {form.formState.errors.countryCode && (
                    <p className="px-1 text-xs text-red-600">
                        {form.formState.errors.countryCode.message}
                    </p>
                )}
            </FormItem>
            {/* Campo para o DDD */}
            <FormItem>
                <Label htmlFor="areaCode">DDD</Label>
                <MaskedInput
                    mask="99"
                    id="areaCode"
                    placeholder="00"
                    autoCapitalize="none"
                    autoComplete="tel-area-code"
                    autoCorrect="off"
                    value={form.watch("areaCode")}
                    onInput={(event) => {
                        form.setValue("areaCode", removeNonNumericChars(event.currentTarget.value));
                    }}
                />
                {form.formState.errors.areaCode && (
                    <p className="px-1 text-xs text-red-600">
                        {form.formState.errors.areaCode.message}
                    </p>
                )}
            </FormItem>
            {/* Campo para o número de telefone */}
            <FormItem>
                <Label htmlFor="number">Telefone</Label>
                <MaskedInput
                    mask="99999-9999"
                    id="number"
                    placeholder="00000-0000"
                    autoCapitalize="none"
                    autoComplete="tel-national"
                    autoCorrect="off"
                    value={form.watch("number")}
                    onInput={(event) => {
                        form.setValue("number", removeNonNumericChars(event.currentTarget.value));
                    }}
                />
                {form.formState.errors.number && (
                    <p className="px-1 text-xs text-red-600">
                        {form.formState.errors.number.message}
                    </p>
                )}
            </FormItem>
        </div>
    );
}

Explicação do Código

  1. Imports e Interfaces: Importamos os módulos necessários e definimos duas interfaces. PhoneInputFormFields define os campos esperados para o formulário de telefone, enquanto PhoneInputProps define as propriedades esperadas pelo componente.

  2. Componente PhoneInput: Este é o componente principal. Ele recebe form do React Hook Form como uma propriedade.

  3. Campos de Entrada: O componente possui três campos de entrada para o código do país, DDD e número de telefone. Cada campo está encapsulado dentro de um FormItem, que é um componente externo que encapsula o rótulo e o campo de entrada.

  4. MaskedInput: Estamos usando um componente MaskedInput para aplicar máscaras aos campos de entrada. Isso ajuda na formatação e validação dos dados inseridos.

  5. Event Handlers: Para cada campo, estamos definindo um manipulador de eventos onInput para atualizar o valor do campo conforme o usuário digita. Este manipulador de eventos chama form.setValue do React Hook Form para atualizar o valor do campo.

  6. Exibição de Erros: Para cada campo, estamos verificando se há erros no estado do formulário (form.formState.errors). Se houver erros, estamos exibindo uma mensagem de erro correspondente.

Erro

No overload matches this call.
  Overload 1 of 4, '(names: readonly Path<T>[], defaultValue?: DeepPartial<T> | undefined): readonly PathValue<T, Path<T>>[]', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'readonly Path<T>[]'.
  Overload 2 of 4, '(name: Path<T>, defaultValue?: PathValue<T, Path<T>> | undefined): PathValue<T, Path<T>>', gave the following error.
    Argument of type '"countryCode"' is not assignable to parameter of type 'Path<T>'.
  Overload 3 of 4, '(callback: WatchObserver<T>, defaultValues?: DeepPartial<T> | undefined): Subscription', gave the following error.
    Argument of type 'string' is not assignable to parameter of type 'WatchObserver<T>'.ts(2769)

Explicação do Erro

O TypeScript está reclamando sobre a sobrecarga de funções que não está sendo resolvida corretamente. Parece que há uma incompatibilidade entre os tipos esperados e os argumentos passados para a função setValue de react-hook-form. Isso pode ser causado por uma má utilização dos tipos genéricos ou por uma inferência de tipos incorreta.

Solicitação de Ajuda

Gostaria de entender por que estou recebendo esse erro e como posso corrigi-lo. Se alguém puder me orientar sobre a melhor abordagem para resolver esse problema, ficaria muito grato!

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật