Reactjs 自定义全局状态挂钩的React Typescript中的显式类型

Reactjs 自定义全局状态挂钩的React Typescript中的显式类型,reactjs,typescript,react-hooks,Reactjs,Typescript,React Hooks,我发现了一个很好的React钩子来管理我的应用程序的全局状态。但是这个例子是用Javascript编写的,我使用的是TypeScript,所以类型需要隐式设置 这是我的商店。ts: import { useState, useEffect } from 'react'; let globalState = {}; let listeners = []; let actions = {}; export const useStore = (shouldListen = true) =>

我发现了一个很好的React钩子来管理我的应用程序的全局状态。但是这个例子是用Javascript编写的,我使用的是TypeScript,所以类型需要隐式设置

这是我的商店。ts:

import { useState, useEffect } from 'react';

let globalState = {};
let listeners = [];
let actions = {};

export const useStore = (shouldListen = true) => {
  const setState = useState(globalState)[1];

  const dispatch = (actionIdentifier, payload) => {
    const newState = actions[actionIdentifier](globalState, payload);
    globalState = { ...globalState, ...newState };

    for (const listener of listeners) {
      listener(globalState);
    }
  };

  useEffect(() => {
    if (shouldListen) {
      listeners.push(setState);
    }

    return () => {
      if (shouldListen) {
        listeners = listeners.filter((li) => li !== setState);
      }
    };
  }, [setState, shouldListen]);

  return [globalState, dispatch];
};

export const initStore = (userActions, initialState) => {
  if (initialState) {
    globalState = { ...globalState, ...initialState };
  }
  actions = { ...actions, ...userActions };
};
这是positions_store.ts,用于管理元素坐标的更新(作为起点):

Typescript为具有“any”类型的隐式的
侦听器、
操作标识符、
有效负载、
用户操作和
初始状态提供了一个错误


我现在挣扎了几个小时,却一事无成。。。感谢您的帮助

实际上,类型很大程度上取决于您如何设计数据结构,这是
侦听器的一个示例
类型:

let listeners: ((state: typeof globalState) => void)[] = [];
let listeners: ((state: typeof globalState) => void)[] = [];