首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我正在努力用typescript完成redux。如何在这些操作中调整所需的类型

我正在努力用typescript完成redux。如何在这些操作中调整所需的类型
EN

Stack Overflow用户
提问于 2019-06-25 12:52:14
回答 1查看 211关注 0票数 0

我只是尝试使用类型安全操作的createStandardAction。我知道它能够设置Action,有效负载的类型。但是我也想使用createStandardAction来设置actionType,比如数字、字符串。我该如何解决这个问题呢?

代码语言:javascript
复制
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,
);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-25 13:56:15

你可以像这样使用接口。

types.js

代码语言:javascript
复制
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

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56747028

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档