使用typeof定义React组件接口并传递Props时遇类型错误
React函数组件复用Zustand Store时的TypeScript类型错误
问题描述
我想要复用TagPanel组件,让它能接收不同的Zustand Store及其对应的Selector,但调用props.store(props.selector, shallow)时触发了TypeScript错误:
Expected 0 arguments, but got 2.
直接调用useListStore(listSelector, shallow)不会报错,但通过props传递store和selector后就会出现类型问题。
相关代码
组件与接口定义
// 引入两个zustand store及其选择器 import { selector as listSelector, useListStore } from '../stores/list-form-store'; import { selector as elementSelector, useElementStore } from '../stores/element-form-store'; import { shallow } from 'zustand/shallow'; export interface ITagPanel { store: typeof useListStore | typeof useElementStore; selector: typeof listSelector | typeof elementSelector; } export function TagPanel(props: ITagPanel) { const {tags, setTags} = props.store(props.selector, shallow); }
Store定义
export const useElementStore = create<IElementStore>()((set) => ({/* ... */})) export const useListStore = create<IListStore>()((set) => ({/* ... */}))
解决方案
问题根源是TypeScript无法识别联合类型中store和selector的对应关系,同时联合类型会丢失函数参数的类型信息。以下是两种可行的解决方式:
方案1:用泛型约束Store与Selector的关联
通过泛型确保传入的store和selector属于同一状态类型,让TypeScript能正确推断函数参数:
import { UseBoundStore, StoreApi } from 'zustand'; // 定义通用Selector类型:提取组件需要的状态切片 type TagSelector<S> = (state: S) => { tags: string[]; setTags: (tags: string[]) => void }; // 定义绑定了Selector的Store类型 type TagStore<S> = UseBoundStore<StoreApi<S>> & { (selector: TagSelector<S>, equalityFn?: (a: any, b: any) => boolean): ReturnType<TagSelector<S>>; }; // 泛型组件接口 export interface ITagPanel<S> { store: TagStore<S>; selector: TagSelector<S>; } // 泛型组件 export function TagPanel<S>(props: ITagPanel<S>) { const { tags, setTags } = props.store(props.selector, shallow); // 组件逻辑... }
使用时TypeScript会自动校验store和selector的匹配性:
<TagPanel store={useListStore} selector={listSelector} /> <TagPanel store={useElementStore} selector={elementSelector} />
方案2:直接传递状态切片(更简洁)
如果不需要在TagPanel内部动态切换selector,可以在父组件中完成store的选择,只传递组件需要的状态和方法:
// 父组件 import { useListStore, listSelector } from '../stores/list-form-store'; import { shallow } from 'zustand/shallow'; function Parent() { const { tags, setTags } = useListStore(listSelector, shallow); return <TagPanel tags={tags} setTags={setTags} />; } // TagPanel组件 export interface ITagPanel { tags: string[]; setTags: (tags: string[]) => void; } export function TagPanel(props: ITagPanel) { // 直接使用props中的tags和setTags }
内容的提问来源于stack exchange,提问作者newprint
相关产品推荐
相关产品推荐

