试图转换成打字稿..无法弄清楚如何制作动作类型和有效负载..我正在使用 useContext 并使用 Reducer

Trying to convert into typescript..cant figure out how to make action types and payload..i am using useContext and use Reducer

正在尝试转换为打字稿..无法弄清楚如何制作动作类型和有效负载..我正在使用 useContext 并使用 Reducer 我基本上希望我的操作从提供的 ./types 的键中获取类型,然后 laso 找出提供 pylaoad 的方式 这是我的状态

import React, { useReducer } from "react"
import AlertContext from "./AlertContext"
import { SHOW_ALERT,REMOVE_ALERT } from "../Types"
import AlertReducer from "./AlertReducer"
import { IAlertState } from "../IAlertState"


export interface typealert{
 variant : string,
text: string,
}
const AlertState = (props : any) =>{

const initialState :IAlertState = {
    alert:{
        variant :'',
        text :''
    }
}

const [state,dispatch] = useReducer(AlertReducer,initialState)

const showAlert =(variant : string,text : string) =>{
    dispatch({type:SHOW_ALERT,payload:{variant,text}})
    setTimeout(()=>{
        setAlert({variant:'',text:''})
    },2000)
}

const setAlert =(alert : typealert) => dispatch({type :REMOVE_ALERT,payload:null})

return(
    <AlertContext.Provider value={{
        alert:state.alert,
        showAlert
    }}>
        {props.children}
    </AlertContext.Provider>
)

}

导出默认 AlertState

这是我的减速机

import React from "react"
import { SHOW_ALERT,REMOVE_ALERT } from "../Types"
import { IAlertState } from "../IAlertState"

export interface IActionTypes{
type : any,
payload : any
}

export default (state : IAlertState ,action : IActionTypes) =>{
switch(action.type)
{
    case SHOW_ALERT:
    return{
        ...state,
        alert:{
            variant : action.payload["variant"],
            text:action.payload["text"]
        }
    }
    case REMOVE_ALERT:
        return{
            ...state,
            alert:{
                variant: '',
                text:''
            }
        }
default : return state
}

}

在此我提供的操作类型是任何类型,但我希望它是来自 ./types 文件的类型

export const SEARCH_USERS = 'SEARCH_USERS'
export const GET_USER ='GET_USER'
export const GET_REPOS = 'GET_REPOS'
export const CLEAR_USERS ='CLEAR_USERS'
export const SHOW_ALERT ='SHOW_ALERT'
export const SET_LOADING ='SET_LOADING'
export const USER_LOADING ='USER_LOADING'
export const REMOVE_ALERT ='REMOVE_ALERT'
type ActionTypes =
  | {
      type: SEARCH_USERS;
      payload: IAlertState["alert"];
    }
  | {
      type: REMOVE_ALERT;
      payload: void;
    }

  | ....

使用联合类型为您的有效载荷和类型建模, 因为类型是区分联合类型的自然标签, 您的代码将得到良好的类型和适当的缩小