[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;
相关推荐
未脱发程序员12 分钟前
【前端】每日一道面试题3:如何实现一个基于CSS Grid的12列自适应布局?
前端·css
三天不学习15 分钟前
Visual Studio Code 前端项目开发规范合集【推荐插件】
前端·ide·vscode
t20071823 分钟前
5.8 react状态管理
javascript·react.js·ecmascript
爱分享的程序猿-Clark38 分钟前
【前端分享】CSS实现3种翻页效果类型,附源码!
前端·css
Code哈哈笑1 小时前
【图书管理系统】深度讲解:图书列表展示的后端实现、高内聚低耦合的应用、前端代码讲解
java·前端·数据库·spring boot·后端
无名之逆1 小时前
Hyperlane: Unleash the Power of Rust for High-Performance Web Services
java·开发语言·前端·后端·http·rust·web
数据潜水员1 小时前
`待办事项css样式
前端·css·css3
_处女座程序员的日常2 小时前
css媒体查询及css变量
前端·css·媒体
GanGuaGua4 小时前
CSS:盒子模型
开发语言·前端·css·html
进取星辰4 小时前
23、Next.js:时空传送门——React 19 全栈框架
开发语言·javascript·react.js