Definitelytyped: [@types/react] createContext – An argument for 'defaultValue' was not provided.

Created on 20 Jul 2019  ·  4Comments  ·  Source: DefinitelyTyped/DefinitelyTyped

Is there any reason of why the argument defaultValue is not optional here?

import * as React from 'react';
import * as firebase from 'firebase/app';

interface AuthProps {
  children: any;
}
interface AuthState {
  user: firebase.User | null;
}
interface AuthContextProps extends AuthState {
  updateUser(user: firebase.User | null): void;
}

export const AuthContext = React.createContext<AuthContextProps>(); // <-- ERROR HERE!

// export const AuthConsumer = AuthContext.Consumer;
export const AuthProvider = (props: AuthProps) => {
  const [state, setState] = React.useState<AuthState>({
    user: null,
  });

  const updateUser = (user: firebase.User | null) => setState({ user });

  return (
    <AuthContext.Provider
      value={{
        updateUser,
        user: state.user,
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};

Docs url: https://reactjs.org/docs/context.html#reactcreatecontext

The defaultValue argument is only used when a component does not have a matching Provider above it in the tree.

I have a matching Provider above in the tree, so I should be able to create a context without set a default value or I'm wrong?

Most helpful comment

Not having a default value is keeping my typescript run build from working. Is there any way to make this optional?

All 4 comments

I'm closing this issue for now. If someone thinks this is a real issue then be free to contribute.

Not having a default value is keeping my typescript run build from working. Is there any way to make this optional?

If you want to compile your code without a default value you can init it with null.

export const AuthContext = React.createContext(null)

~The null solution no longer works for me. I'll file a new issue.~

Edit: no, https://github.com/DefinitelyTyped/DefinitelyTyped/pull/34854 mentions why. AH well.

Was this page helpful?
0 / 5 - 0 ratings