typescript 类型“接口”上不存在属性|未定义”

huwehgph  于 2023-06-07  发布在  TypeScript
关注(0)|答案(1)|浏览(247)

我有这样的背景

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|未定义
据我所知,我应该在前面的接口中输入属性,那么为什么我会得到这个错误呢?
请帮帮我谢谢你。

5rgfhyps

5rgfhyps1#

createContext的泛型类型被设置为Partial<SearchPageContextInterface>。这意味着SearchPageContextInterface中的每个变量都是可选的。因此,编译器推断searchBoolean的类型为SearchBooleanContextInterface | undefined
虽然SearchBooleanContextInterface包含isSearched,但undefined显然不包含,这会导致编译器返回错误。
您可以将Partial<SearchPageContextInterface>SearchPageContextInterface交换,或者将代码更改为

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.
}

相关问题