我只是尝试使用typesafe-actions的createStandardAction。 我了解它能够设置Action(有效负载)类型。但是我想在动作中设置actionType,例如数字,字符串,以及使用createStandardAction。 我该如何解决这个问题。
import { createStandardAction } from 'typesafe-actions';
import { handleActions } from 'redux-actions';
import { produce } from 'immer';
const COUNT = 'workers/COUNT';
const INCREMENT = 'workers/INCREMENT';
//workersActions.count'type is any
//But I wanna this type is number.
export const workersActions = {
count: createStandardAction(COUNT)<number>(),
increment: createStandardAction(INCREMENT)<void>(),
};
type Increment = ReturnType<typeof workersActions.increment>;
export type WorkerState = {
count: number;
};
const initialState : WorkerState = {
count : 0
}
const workers = handleActions<WorkerState, any>(
{
[INCREMENT]: (state, action: Increment) => {
return produce(state, draft => {
draft.count = action.payload + 1;
});
},
},
initialState,
);
答案 0 :(得分:1)
您可以使用这样的界面。
types.js
export const SEND_MESSAGE = 'SEND_MESSAGE'
export const DELETE_MESSAGE = 'DELETE_MESSAGE'
interface SendMessageAction {
type: typeof SEND_MESSAGE
payload: Message
}
interface DeleteMessageAction {
type: typeof DELETE_MESSAGE
meta: {
timestamp: number
}
}
export type ChatActionTypes = SendMessageAction | DeleteMessageAction
actions.ts
import { Message, SEND_MESSAGE, DELETE_MESSAGE, ChatActionTypes } from './types'
// TypeScript infers that this function is returning SendMessageAction
export function sendMessage(newMessage: Message): ChatActionTypes {
return {
type: SEND_MESSAGE,
payload: newMessage
}
}
// TypeScript infers that this function is returning DeleteMessageAction
export function deleteMessage(timestamp: number): ChatActionTypes {
return {
type: DELETE_MESSAGE,
meta: {
timestamp
}
}
}
了解更多详细信息:https://redux.js.org/recipes/usage-with-typescript#type-checking-state