[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;
相关推荐
独泪了无痕15 分钟前
自动导入 AutoImport:告别手动引入依赖,优化Vue3开发体验
前端·vue.js·typescript
GDAL31 分钟前
MANIFEST.in简介
linux·服务器·前端·python
XPoet1 小时前
AI 编程工程化:Command——给你的 AI 员工编一套操作手册
前端·后端·ai编程
C_心欲无痕1 小时前
前端实现文件下载的完整流程
前端·状态模式
Fighting_p1 小时前
【element UI】el-select 组件下拉数据某一行文字过多时,文字换行展示,避免el-select下拉框被撑宽,导致页面过丑
前端·javascript
王家视频教程图书馆2 小时前
vue3从本地选择一个视频 展示到视频组件中
前端·javascript·音视频
天外来鹿2 小时前
Map/Set/WeakMap/WeakSet学习笔记
前端·javascript·笔记·学习
Luna-player2 小时前
前端中stylus是干嘛用的
前端·css·stylus
CHQIUU2 小时前
解决 npm 全局安装 EACCES 权限问题(macOS 篇)
前端·macos·npm
程序员鱼皮2 小时前
OpenClaw接入飞书保姆级教程,几分钟搞定手机养龙虾!
前端·人工智能·后端