我已经使用Zustand创建了以下商店:
import create from "zustand"
const useStore = create((set) => ({
show: false,
toggleShow: () => set((state) => ({ show: !state.show })),
}))我认为这是切换show值的正确方法。然而,typescript并不满意--它在!state.show中的show下面有一条红色的弯弯曲曲的线,并带有以下错误消息:
Property 'show' does not exist on type 'object'.ts(2339)
any你知道为什么我会收到这个错误信息,以及我如何使用Zustand正确地设置切换功能吗?
谢谢。
发布于 2021-08-26 20:39:37
Typescript不知道状态应该是什么样子,所以它假设状态是一个普通对象。
为了解决这个问题,你可以为你的商店定义一个类型。然后,您可以将该类型作为泛型传递给create函数:
type MyStore = {
show: boolean;
toggleShow: () => void;
};
// note the "<MyStore>" next to create
const useStore = create<MyStore>((set) => ({
show: false,
toggleShow: () => set((state) => ({ show: !state.show})),
}))这使得typescript知道哪些属性会出现在你的商店里。它将不再为!state.show部件抛出错误,并且无论您何时使用存储区,它都将提供有意义的自动完成功能。
https://stackoverflow.com/questions/68183319
复制相似问题