0

I keep wanting to use a use cotext hook but i learned to use use context by putting an empty {} in the create context thing. But it is giving me errors. Not assignable to {} and type any not available.

import React from "react";

type data = {
    state?: any;
};

const state = 1;
export const BasicContext = React.createContext<data>(state);

this gave an error

Type '1' has no properties in common with type 'data'.(2559)

How do i fix it? It is weird?

kelsny
  • 23,009
  • 3
  • 19
  • 48
  • There's a syntax error in your post, and `React` is not defined. And when I do correct these, assuming they are typos, I get completely unrelated errors: https://tsplay.dev/WkDL2w – kelsny Mar 19 '23 at 22:42
  • almost import React from "react"; import { createContext } from "react"; type data={ state?: any; } const state = 1; export const BasicContext = React.createContext(state) this still gives –  Mar 19 '23 at 22:46
  • Type '1' has no properties in common with type 'data'.ts(2559) –  Mar 19 '23 at 22:46
  • Yeah... that is not the error shown in your post... Can you update your post to correct these errors? – kelsny Mar 19 '23 at 22:47
  • To fix it, just give it the right type. It expects an object with a `state` property, but you're giving it a number. https://tsplay.dev/WvqvRm – kelsny Mar 19 '23 at 22:48
  • like this is still gives error import React from "react"; import { useState } from "react"; type data = { state?: any; }; const [open,setOpen] = useState(false) export const BasicContext = React.createContext(open); –  Mar 19 '23 at 22:51
  • sory formatting hold on –  Mar 19 '23 at 22:51
  • Did you read my last comment and click on the playground link? – kelsny Mar 19 '23 at 22:51
  • https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDG8BmUIjgIilQ3wG4AoUSWOAbzgFcBnJAZRhRiTgF85tcBIuhhly5GAE8w3ACacUcALx1ycdXCYcuAfgBccFADtJFHhXJoIRrXADaEGUYA0LGAHknAXWWMW7TiQACkwUABsWAEpyJAAPangrG3gAIRQmYDQAYWsuWPgVZBEAOjRhLhyjPJgAHnkOAD4gxyQjSIsgA –  Mar 19 '23 at 22:52
  • Again, give it the correct type: https://tsplay.dev/WyqadW – kelsny Mar 19 '23 at 22:52
  • can you send as answer so i can mark it @vr –  Mar 19 '23 at 22:53

1 Answers1

0

You're giving it the wrong type. Since you used createContext<data>, it expects an initial value with the type data. Because data is an object type, and you passed a number, TypeScript throws an error.

You can wrap your state in brackets taking advantage of property initializer shorthand to easily create an object that matches the data type:

const state = 1;
export const BasicContext = React.createContext<data>({ state });
//                 same as passing { state: state } - ~~~~~~~~~

Playground

kelsny
  • 23,009
  • 3
  • 19
  • 48