Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript HOC with React.createContext

I have this .js snippet that I need to translate into Typescript.

import React from 'react';

const FirebaseContext = React.createContext(null)

export const withFirebase = Component => props => (
    <FirebaseContext.Consumer>
        {firebase => <Component {...props} firebase={firebase} />}
    </FirebaseContext.Consumer>
)

export default FirebaseContext

my best guess is

const FirebaseContext = React.createContext(null)

export const withFirebase = (Component: React.ComponentClass) => (props: any) => (
    <FirebaseContext.Consumer>
        {firebase => <Component {...props} firebase={firebase} />}
    </FirebaseContext.Consumer>
)

but when I try to use the context – by passing a new Firebase():

import React from 'react';
import ReactDOM from 'react-dom';

import './index.css';
import * as serviceWorker from './serviceWorker';

import App from './components/App';
import Firebase, { FirebaseContext } from './components/Firebase';

ReactDOM.render(
    <FirebaseContext.Provider value={new Firebase()}>
        <App />
    </FirebaseContext.Provider>,
    document.getElementById('root'),
);

serviceWorker.unregister()

in this case – I get Type 'Firebase' is not assignable to type 'null'.

like image 847
Frank Avatar asked Jan 27 '23 16:01

Frank


1 Answers

You seem to have not specified any type to createContext. Adding a Firebase type to it should work

const FirebaseContext = React.createContext<Firebase | null>(null);
like image 186
Shubham Khatri Avatar answered Jan 31 '23 23:01

Shubham Khatri