I am using CreateContext in Typescript and I can see why there is a problem with the code but I cannot work out how to resolve it. Its a basic use of typesafe TX to make state and (useReducer) dispatch available in a component hierarchy
The sandbox: https://codesandbox.io/s/typescript-usereducer-todo-lk391?file=/src/App.tsx
The context interface:
export interface ContextInterface {
state: AppState;
dispatch: (action: ActionType) => void;
}
Using the interface to createContext (I think it has to be a partial because createContext wont take zero args)
const TodoContext = createContext<Partial<ContextInterface>>({});
The context is initialised in my parent component:
let [state, dispatch] = useReducer(reducer, initialState);
...
return (
<TodoContext.Provider value={{ state, dispatch }}>
...
When I useContext TS reports Cannot invoke an object which is possibly 'undefined'.ts(2722), however the console.log executes as expected.
let { dispatch } = useContext(TodoContext);
console.log("dispatch", dispatch);
Is there a way to correctly define the Context object and remove the error?