打字稿中的调度类型

时间:2021-03-01 08:19:32

标签: reactjs typescript redux react-redux

因为我认为在打字稿中我们应该尽可能避免使用“any”类型我正在重写所有 anys 以将它们转换为更精确的类型但是当我尝试更改类型“any”时我遇到了问题' react redux 的调度函数。我不知道用什么代替它?

themeActions.ts :

export const SWITCH_THEME: string = "SWITCH_THEME";

export const switchTheme = (theme: string) => {

    return (dispatch: any) => {
        
        dispatch({ type: SWITCH_THEME, theme: theme })
        localStorage.setItem('theme', theme);

    }

}

themeReducer.ts :

import {SWITCH_THEME} from './themeActions';

const initialState = {
    theme: localStorage.getItem('theme') === 'dark' ? 'dark' : 'light'
}

const themeReducer = (state = initialState, action: {type: string, theme: string}) => {
    switch (action.type) {
        case SWITCH_THEME:
            return {
                ...state,
                theme: action.theme
            }
            default:
                return state
    }
}

export default themeReducer;

1 个答案:

答案 0 :(得分:1)

只需使用 import { Dispatch } from 'redux'

export const switchTheme = (theme: string) => {

    return (dispatch: Dispatch) => {
        
        dispatch({ type: SWITCH_THEME, theme: theme })
        localStorage.setItem('theme', theme);

    }

}