1

So I found the 5-6 other questions I actually kinda fixed it with " ! " operator, so don't delete the question for duplication, but what I don't understand is the variable is not an object. So this is the context;

import { createContext } from "react";

interface PlanetInfos {
  planetName: string;
  radius: string;
  distanceFromSun?: string;
  numberOfMoons?: string;
  averageTemperature: string;
  svg: string;
}

type ContextProps = {
  miliSeconds: number;
  setmiliSeconds: any;
  planetInfos: PlanetInfos[];
};

const PlanetContext = createContext<Partial<ContextProps>>({});

export default PlanetContext;

here is the App.js where I define the miliseconds for example;

const App: React.FC = () => {
  const [miliSeconds, setmiliSeconds] = useState(10000);

  return (
    <PlanetContext.Provider
      value={{
        miliSeconds,
        setmiliSeconds,
        planetInfos,
      }}
    >
      <div className="App">
        <SideBar />
        <Planets />
      </div>
    </PlanetContext.Provider>
  );
};

export default App;

So in wherever I do this and use miliseconds somewhere in the component;

const { miliSeconds } = useContext(PlanetContext);

It says "Object is possibly undefined" and it doesn't make sense for me. Because it was never an object. So is there any solution besides putting exclamation mark everywhere in the app?

7
  • It is because you used partial : Partial<ContextProps>. Partials makes everything "optional" = the type you mentioned or "undefined" Commented Mar 11, 2021 at 19:35
  • 2
    If none of the properties is supposed to be "undefiend", you don't need to use Partial, you can write : createContext<ContextProps>({} as ContextProps) ; or perhaps createContext({} as ContextProps) ; Commented Mar 11, 2021 at 19:47
  • 2
    And you can improve : setmiliSeconds: (ms: number) => void Commented Mar 11, 2021 at 19:50
  • 1
    oh man thanks, this kinda resolved everything. just couldn't get the ms stuff in the parameter though Commented Mar 11, 2021 at 19:58
  • 2
    no, I change the createContext as you said and didn't get any errors. I removed the partial Commented Mar 11, 2021 at 20:02

1 Answer 1

2
 createContext<Partial<ContextProps>>({});

I think this code leads to define the type of the context not equals to ContextProps, but all object fields will be possibly undefined. Partial util type does this. Then, even if you define values for the context in App component before using it, typescript knows nothing about this, and infer a type of milliseconds as one from Partical, so it will be number | undefined

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.