我只是尝试使用类型安全操作的createStandardAction。我知道它能够设置Action,有效负载的类型。但是我也想使用createStandardAction来设置actionType,比如数字、字符串。我该如何解决这个问题呢?
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,
);发布于 2019-06-25 13:56:15
你可以像这样使用接口。
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 | DeleteMessageActionactions.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
https://stackoverflow.com/questions/56747028
复制相似问题