我最近为我的react项目切换到Typescript,并且得到了带有redux(thunk)工作的Typescript。我仍然想知道是否可以将接口“绑定”到调度动作,以便检查其形状。
我的actionCreator的代码:
import { Message, SEND_MESSAGE, DELETE_MESSAGE, GET_MESSAGES_SUCCESS, GET_MESSAGES_FAILED, GET_MESSAGES, ChatActionTypes, ChatState } from './types';
import { ActionCreator, Dispatch } from 'redux';
import { ThunkAction } from 'redux-thunk';
import axios from "axios";
export const getMessages: ActionCreator<ThunkAction<Promise<any>, ChatState, null, ChatActionTypes>> = () => {
console.log('i get called')
return async (dispatch: Dispatch) => {
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/todosdffd');
console.log(response)
dispatch({
type: GET_MESSAGES_SUCCESS,
payload: {
loading: false,
data: response.data,
}
})
} catch (error) {
console.log('error triggered')
dispatch({
type: typeof GET_MESSAGES_FAILED,
payload: {
loading: false,
error: {error }
}
})
}
}
}
export function sendMessage(newMessage: Message): ChatActionTypes {
return {
type: SEND_MESSAGE,
payload: newMessage
}
}
export function deleteMessage(timestamp: number): ChatActionTypes {
return {
type: DELETE_MESSAGE,
meta: {
timestamp
}
}
}
我的类型文件
export const SEND_MESSAGE = 'SEND_MESSAGE';
export const DELETE_MESSAGE = 'DELETE_MESSSAGE' ;
export const GET_MESSAGES = 'GET_MESSSAGES' ;
export const GET_MESSAGES_SUCCESS = 'GET_MESSAGES_SUCCESS' ;
export const GET_MESSAGES_FAILED = 'GET_MESSAGES_FAILED' ;
export interface Message {
user: string,
message: string,
timeStamp: number
}
export interface ChatState {
messages: Message[]
}
interface SendMessageAction {
type: typeof SEND_MESSAGE,
payload: Message
}
interface DeleteMessageAction {
type: typeof DELETE_MESSAGE,
meta: {
timestamp: number
}
}
interface GetMessagesAction {
type: typeof GET_MESSAGES,
payload: {
loading: boolean
}
}
interface GetMessagesFailedAction {
type: typeof GET_MESSAGES_FAILED,
payload: {
loading: boolean,
error: object
}
}
interface GetMessagesSuccessAction {
type: typeof GET_MESSAGES_SUCCESS,
payload: {
loading: boolean,
data: any[]
}
}
export type ChatActionTypes = SendMessageAction | DeleteMessageAction | GetMessagesAction | GetMessagesFailedAction | GetMessagesSuccessAction;
我想做的事情:
dispatch<ChatActionTypes>({ ... })
但这不起作用。将接口直接放入actionCreator的代码并将其设置为调度的类型也没有用。
任何建议将不胜感激!