Help understanding contexts in typescript
Unanswered
Masai Lion posted this in #help-forum
Masai LionOP
I'm new to react. I was reading their documentation on contexts and they have an example which perfectly fits what I'd like to do:
https://codesandbox.io/p/sandbox/react-dev-72nnpt?file=%2Fsrc%2FApp.js&utm_medium=sandpack
(taken from https://react.dev/reference/react/useContext)
The code is written in JS, the instant I tried porting it over to TS it began complaining about the types. I could just keep everything in JS but I'd like to learn how to do it in TS, and was wondering if anyone could help me figure that out. I initially thought I'd just have to add types to one or two things but it seems more complex than that.
Thank you.
https://codesandbox.io/p/sandbox/react-dev-72nnpt?file=%2Fsrc%2FApp.js&utm_medium=sandpack
(taken from https://react.dev/reference/react/useContext)
The code is written in JS, the instant I tried porting it over to TS it began complaining about the types. I could just keep everything in JS but I'd like to learn how to do it in TS, and was wondering if anyone could help me figure that out. I initially thought I'd just have to add types to one or two things but it seems more complex than that.
Thank you.
6 Replies
all you need to do to type the context is to give a type to the
createContext call. what exactly are you having issues with?Masai LionOP
sorry if I'm missing something obvious but. here's the code I have so far. I want to make the context an array of strings:
const BoardContext = createContext<string[]>(null);
export default function Board() {
const [board, setBoard] = useState<string[]>(null);
return (
<BoardContext.Provider value={{board, setBoard}}>
<div></div>
</BoardContext.Provider>
);
}I've tried changing
null into an empty array and that doesn't seem to work eitheryou said that the value of the context is
string[] but you are trying to pass an object so yeah thats not gonna workyou need to type the context with the exact value you are gonna give it
and if you start the context with
null then the type should include it as well with an union, e.g. string[] | null