I have this context
export type SearchBooleanContextInterface = {
isSearched: IsSearched,
setIsSearched?: Dispatch<SetStateAction<IsSearched>>
}
export interface SearchPageContextInterface{
value: string,
payload: any,
searchBoolean: SearchBooleanContextInterface
}
export const SearchPageContext = createContext<Partial<SearchPageContextInterface>>({});
I define the value here:
<SearchPageContext.Provider value={{value: "", payload: "", searchBoolean: {isSearched, setIsSearched}}}>
But when I want to use the context and then destructure "seachBoolean" property like this:
const SearchPage = useContext(SearchPageContext);
const {searchBoolean} = SearchPage;
const {isSearched} = searchBoolean;
it returns this error message Property 'isSearched' does not exist on type 'SearchBooleanContextInterface | undefined'.
To my understanding, I should have typed the property in earlier interface, so why am I getting this error?
Please help. Thank you.
createContext's generic type is set to bePartial<SearchPageContextInterface>. This means that every variable inSearchPageContextInterfacewill be optional. As such, the compiler inferssearchBoolean's type to beSearchBooleanContextInterface | undefined.While
SearchBooleanContextInterfacecontainsisSearched,undefinedobviously does not, which causes the compiler to return the error.You could either swap
Partial<SearchPageContextInterface>withSearchPageContextInterface, or change your code to something to the lines of