Come si usa useRef con Typescript / Formik?

Sep 02 2020

Sto passando una refproprietà nel mio FieldInput personalizzato che utilizzo per la convalida Formik del mio modulo. Tuttavia, fornisce alcuni errori di dattiloscritto. Ad esempio, nella mia funzione:

    const handleSubmitForm = (
    values: FormValues,
    helpers: FormikHelpers<FormValues>,
  ) => {

    setShowFlatList(true);
    Keyboard.dismiss();
    helpers.resetForm();
    if (fieldRef && fieldRef.current){
          fieldRef.current.blur();}
    helpers.resetForm();
  };

Ottengo un errore su fieldRef.current that Object is possibly 'undefined'.. Ho pensato che l'aggiunta della condizione if lo avrebbe risolto, ma non è stato così. Inoltre, quando invio il modulo, ricevo un avviso

Warning: An unhandled error was caught from submitForm()
Error: "fieldRef.current.blur is not a function. (In 'fieldRef.current.blur()', 'fieldRef.current.blur' is undefined)" in handleSubmitForm 

Allo stesso modo, nel mio componente FieldInput personalizzato in cui utilizzo ref={fieldRef}, ricevo un errore che:

Type '{ ref: MutableRefObject<undefined>; setFieldTouched: (field: string, isTouched?: boolean | undefined, shouldValidate?: boolean | undefined) => void; handleChange: { ...; }; ... 4 more ...; placeholderText: string; }' is not assignable to type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.
  Property 'ref' does not exist on type 'IntrinsicAttributes & FieldInputProps & { children?: ReactNode; }'.ts(2322)

Come posso risolverli?

Ecco un codeandbox:

https://snack.expo.io/@nhammad/jealous-beef-jerky-fix

Risposte

1 zhuber Sep 07 2020 at 11:01

Se si esaminano i tipi generici correnti del forwardRefmetodo, il primo parametro è unknown. Basta cambiare il metodo di immissione della firma in

export const FieldInput = React.forwardRef<Input, FieldInputProps>(...)

Typescript risolverà automaticamente il tipo corretto in base al forwardReftipo restituito dal metodo.