Typescript / FormikでuseRefを使用する方法は?

Sep 02 2020

refフォームのFormik検証に使用するカスタムFieldInputにプロパティを渡します。ただし、Typescriptエラーがいくつか発生します。たとえば、私の関数では:

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

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

fieldRef.currentでエラーが発生しObject is possibly 'undefined'.ます。if条件を追加すると修正されると思いましたが、修正されませんでした。また、フォームを送信すると、次のような警告が表示されます

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 

同様に、を使用するカスタムFieldInputコンポーネントで ref={fieldRef}、次のエラーが発生します。

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)

どうすればこれらを修正できますか?

コードサンドボックスは次のとおりです。

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

回答

1 zhuber Sep 07 2020 at 11:01

forwardRefメソッドの現在のジェネリック型を調べると、最初のパラメーターはunknownです。入力の署名方法をに変更するだけです

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

Typescriptは、forwardRefメソッドの戻り値の型に基づいて正しい型を自動的に解決します。