[react] 优雅解决typescript动态获取redux仓库的类型问题

store.getState()是可以获取总仓库的

先拿到函数的类型

再用ReturnType<T>

它是 TypeScript 中的一个内置条件类型,用于获取某个函数类型 T 的返回值类型

代码

javascript 复制代码
    // 先拿总仓库的函数类型
    type StatefuncType = typeof store.getState;
    //再拿函数类型T的返回值类型
    type StateType = ReturnType<StatefuncType>;
    const counter = useSelector((state: StateType) => {
        return state.couterSlice;
    });

可以直接一步到位

javascript 复制代码
    type StateType = ReturnType<typeof store.getState>;

也可以用这样

javascript 复制代码
const a = store.getState();
    type a1 = typeof a;

还麻烦怎么办?我想在导入的时候自带类型呢?

用TypedUseSelectorHook 加自定义useSelector

参考:TypeScript 快速开始 | Redux 中文官网

javascript 复制代码
import { configureStore } from '@reduxjs/toolkit';
import { useSelector, TypedUseSelectorHook } from 'react-redux';
import couterSlice from './modules/counter';

const store = configureStore({
    reducer: {
        couterSlice,
    },
});
export type storeType = ReturnType<typeof store.getState>;

export const useAppSelector: TypedUseSelectorHook<storeType> = useSelector;
export default store;
相关推荐
FRing035 小时前
vue3干货总结3(defineOptions(Vue3.3)、defineModel(Vue3.4)、Pinia)
开发语言·前端·vue.js·vue3
Bczheng15 小时前
组件化服务端渲染模式SSR
前端
whitelbwwww7 小时前
CUDA C++实战--中级
开发语言·前端·c++
张紫娃7 小时前
Chrome插件-Stylus(屏蔽博客广告)
前端·chrome·stylus
Yannik7 小时前
在 Apple Silicon Mac 上用 Jenkins + Fastlane 搭建 iOS CI:从自动打包到 MR 检查流水线的完整实践
前端
Nayana7 小时前
《Web 到 HarmonyOS》-- 打包:Vite 产物 → HAP / HAR / HSP
前端
inksci7 小时前
用飞帆做了个小网页
前端·javascript·css·html
去伪存真7 小时前
被 pnpm 打包坑惨后,我彻底盘明白了硬链接与软链接
前端·electron
zhensherlock8 小时前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
tryCbest13 小时前
Vue3——第 22 篇:Pinia——新一代状态管理(上)
前端·javascript·vue.js