DEV Community

Vu Anh Duc
Vu Anh Duc

Posted on

React Native: Final Form, react-native-paper and typescript

use react-final-form with react-native-paper

Problem:

type TextFieldProps = FieldRenderProps<string, any> & {
  label?: string;

};

const TextField: React.FC<TextFieldProps> = ({
  input,
  meta,
  label,
  ...rest
}: TextFieldProps) => (
  <TextInput label={label} type="text" {...input} {...rest} />
);

Khi sử dụng TextInput của react-native-paper với Field của react-final-form, typescript compiler sẽ thông báo lỗi:


Type '{ name: string; onBlur: (event?: FocusEvent<any> | undefined) => void; onChange: (event: any) => void; onFocus: (event?: FocusEvent<any> | undefined) => void; type: string; value: string; checked?: boolean | undefined; multiple?: boolean | undefined; label: string | undefined; }' is not assignable to type 'Pick<TextInputProps, "error" | "value" | "label" | "ref" | "style" | "allowFontScaling" | "autoCapitalize" | "autoCorrect" | "autoFocus" | "blurOnSubmit" | "caretHidden" | "contextMenuHidden" | ... 97 more ... | "dense">'
  Types of property 'onBlur' are incompatible.
    Type '(event?: FocusEvent<any> | undefined) => void' is not assignable to type '((e: NativeSyntheticEvent<TextInputFocusEventData>) => void) & ((args: any) => void)'.
      Type '(event?: FocusEvent<any> | undefined) => void' is not assignable to type '(e: NativeSyntheticEvent<TextInputFocusEventData>) => void'.
        Types of parameters 'event' and 'e' are incompatible.
          Property 'relatedTarget' is missing in type 'NativeSyntheticEvent<TextInputFocusEventData>' but required in type 'FocusEvent<any>'.

Causes

Nguyên nhân là do signature của thuộc tính onBlur của final-formreact-native-paper là khác nhau.

Cũng hợp lý, vì vốn dĩ final-form không nhắm đến react-native.

Fix

Để khắc phục vấn đề này, cần khai báo thêm thuộc tính onBluronFocus với signature giống với của react-native-paper.


type TextFieldProps = FieldRenderProps<string, any> & {
  label?: string;
  onBlur: ((e: NativeSyntheticEvent<TextInputFocusEventData>) => void) &
    ((args: any) => void);
  onFocus: ((e: NativeSyntheticEvent<TextInputFocusEventData>) => void) &
    ((args: any) => void);
};

const TextField: React.FC<TextFieldProps> = ({
  input,
  meta,
  label,
  ...rest
}: TextFieldProps) => (
  <TextInput label={label} type="text" {...input} {...rest} />
);

Conclusion

still don't understand.
We learn javascript because of its dynamic types. And now we learn typescript to enable strong-types for javascript.

Top comments (0)