I'm just starting to use Typescript in React Native and need help with refs and their types.
Please, see my code below:
type MyComponentProps = { ref?: React.RefObject<typeof MyComponentViewNative>; style?: ViewStyle;};type MyComponentState = { permissionsGranted?: Boolean;};const ComponentName = 'MyComponentView';const MyComponentViewNative = UIManager.getViewManagerConfig(ComponentName) != null ? requireNativeComponent<MyComponentProps>(ComponentName) : () => { throw new Error(LINKING_ERROR); };export class MyComponentView extends React.PureComponent<{}, {}> { private viewRef: React.RefObject<typeof MyComponentViewNative> = React.createRef<typeof MyComponentViewNative>(); public state: MyComponentState = { permissionsGranted: false, }; async componentDidMount() { ... this.setState({ permissionsGranted: true }); } start(filePath: String) { callViewMethod(this.viewRef, 'start', filePath); } render() { const { permissionsGranted } = this.state; return permissionsGranted ? (<MyComponentViewNative {...this.props} ref={this.viewRef} /> ) : (<View {...this.props} /> ); }}function callViewMethod( viewRef: React.RefObject<typeof MyComponentViewNative>, methodName: string, ...params: any[]) { if (viewRef.current == null) { return; } if (Platform.OS === 'ios') { NativeModules.MyComponentViewNative[methodName].apply( NativeModules.MyComponentViewNative, [findNodeHandle(viewRef.current), ...params] ); } else if (Platform.OS === 'android') { UIManager.dispatchViewManagerCommand( findNodeHandle(viewRef.current), methodName, params ); }}
My goal is to create a native component wrapper class MyComponentView
, get a ref viewRef
to an instance of the native component MyComponentViewNative
in it and call it's method start
. Seems I'm using ref the right way (at list it worked for me in plain JS many times), but setting its type is a thing I can't figure out.
So, tsc gives me a bunch of errors a-la the following one:
src/index.tsx:124:23 - error TS2345: Argument of type 'HostComponent<MyComponentProps> | (() => never)' is not assignable to parameter of type 'number | ComponentClass<any, any> | Component<any, any, any> | null'. Type '() => never' is not assignable to type 'number | ComponentClass<any, any> | Component<any, any, any> | null'.124 [findNodeHandle(viewRef.current), ...params]
What am I doing wrong? What type should I use for the viewRef property? Or. maybe, I can somehow skip setting types explicitly?