我有这样的背景
export type SearchBooleanContextInterface = {
isSearched: IsSearched,
setIsSearched?: Dispatch<SetStateAction<IsSearched>>
}
export interface SearchPageContextInterface{
value: string,
payload: any,
searchBoolean: SearchBooleanContextInterface
}
export const SearchPageContext = createContext<Partial<SearchPageContextInterface>>({});
我在这里定义值:
<SearchPageContext.Provider value={{value: "", payload: "", searchBoolean: {isSearched, setIsSearched}}}>
但是当我想使用上下文,然后像这样解构“seachBoolean”属性时:
const SearchPage = useContext(SearchPageContext);
const {searchBoolean} = SearchPage;
const {isSearched} = searchBoolean;
它返回此错误消息Property 'isSearched' does not exist on type 'SearchBooleanContextInterface|未定义
据我所知,我应该在前面的接口中输入属性,那么为什么我会得到这个错误呢?
请帮帮我谢谢你。
1条答案
按热度按时间5rgfhyps1#
createContext
的泛型类型被设置为Partial<SearchPageContextInterface>
。这意味着SearchPageContextInterface
中的每个变量都是可选的。因此,编译器推断searchBoolean
的类型为SearchBooleanContextInterface | undefined
。虽然
SearchBooleanContextInterface
包含isSearched
,但undefined
显然不包含,这会导致编译器返回错误。您可以将
Partial<SearchPageContextInterface>
与SearchPageContextInterface
交换,或者将代码更改为