我遇到了问题,包括 Typescript 中 React 上下文中的图例状态。 Legend 版本 (
@legendapp/state
) 是 3.0.0-alpha.38
,React 版本是 18.2.0
,Typescript 版本是 5.3.3
。我的设置是:
type Store = {
stuff: string;
}
export type StevenContextType = {
store: Observable<Store>;
};
const store$ = useObservable({
stuff: "yo"
});
export const StevenContext = React.createContext<StevenContextType | null>(null);
<StevenContext.Provider value={{ store$ }}>
我收到的错误消息是:
Type {store$: ObservableObjectFunctions<ObservableProps<{stuff: string}> & NonObservableProps<{stuff: string}>> & ObservableChildren<ObservableProps<{stuff: string}>> & ObservableFunctionChildren<NonObservableProps<{stuff: string}>>} is not assignable to type StevenContextType | null
任何帮助将不胜感激;我确信有一个打字的细微差别,我只是没有掌握,但我无法弄清楚。
在
ts const store$ = useObservable({ stuff: "yo" });
使用
useObservable
代替 observable
钩子来创建商店。这是 Legend 库中创建可观察对象的正确函数
您的问题似乎是由 useObservable 挂钩返回的 store$ 对象的类型引起的。你的 useObservable 钩子很可能没有返回 StevenContext 所期望的内容。您可以首先确保您提供给 StevenContext 的类型由 useObservable 挂钩返回的内容正确描述。
type Store = {
stuff: string;
};
export type StevenContextType = {
store$: Observable<Store>;
};
const store$ = useObservable<Store>({
stuff: "yo"
});
export const StevenContext = React.createContext<StevenContextType | null>(null);
<StevenContext.Provider value={{ store$ }}>
if after explicitly typing the observable using the correct return from the useObservable hook and updating the SteveContextType to match the observable object, and you still encounter this issue you might need to check your @legendapp/state for the correct types to use