Property does not exist on type "Interface | undefined"

40 Views Asked by At

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.

1

There are 1 best solutions below

0
Watson Drizet On

createContext's generic type is set to be Partial<SearchPageContextInterface>. This means that every variable in SearchPageContextInterface will be optional. As such, the compiler infers searchBoolean's type to be SearchBooleanContextInterface | undefined.

While SearchBooleanContextInterface contains isSearched, undefined obviously does not, which causes the compiler to return the error.

You could either swap Partial<SearchPageContextInterface> with SearchPageContextInterface, or change your code to something to the lines of

const SearchPage = useContext(SearchPageContext);
const {searchBoolean} = SearchPage;
const isSearched = searchBoolean?.isSearched;
if(isSearched === undefined) {
    // What would you like to do if `isSearch` is not defined?
} else {
    // `isSearched` is properly defined. Continue as expected.
}