如何在 TypeScript 中输入 Redux 动作和 Redux 减速器? [英] How to type Redux actions and Redux reducers in TypeScript?

查看:44
本文介绍了如何在 TypeScript 中输入 Redux 动作和 Redux 减速器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 redux 中转换 action 参数的最佳方法是什么 reducer 与打字稿?可能会出现多个操作接口,它们都扩展了具有属性类型的基本接口.扩展的动作接口可以有更多的属性,这些属性在动作接口之间都是不同的.下面是一个例子:

What is the best way to cast the action parameter in a redux reducer with typescript? There will be multiple action interfaces that can occur that all extend a base interface with a property type. The extended action interfaces can have more properties that are all different between the action interfaces. Here is an example below:

interface IAction {
    type: string
}

interface IActionA extends IAction {
    a: string
}

interface IActionB extends IAction {
    b: string
}

const reducer = (action: IAction) {
    switch (action.type) {
        case 'a':
            return console.info('action a: ', action.a) // property 'a' does not exists on type IAction

        case 'b':
            return console.info('action b: ', action.b) // property 'b' does not exists on type IAction         
    }
}

问题是 action 需要被转换为可以访问 IActionAIActionB 的类型,这样reducer 就可以同时使用两者action.aaction.a 不会抛出错误.

The problem is that action needs to be cast as a type that has access to both IActionA and IActionB so the reducer can use both action.a and action.a without throwing an error.

我有几个解决这个问题的想法:

I have several ideas how to work around this issue:

  1. action 转换为 any.
  2. 使用可选的接口成员.

示例:

interface IAction {
    type: string
    a?: string
    b?: string
}

  1. 为每种操作类型使用不同的 reducer.

在打字稿中组织 Action/Reducers 的最佳方式是什么?提前致谢!

What is the best way to organize Action/Reducers in typescript? Thank you in advance!

推荐答案

With Typescript 2's 标记联合类型您可以执行以下操作

With Typescript 2's Tagged Union Types you can do the following

interface ActionA {
    type: 'a';
    a: string
}

interface ActionB {
    type: 'b';
    b: string
}

type Action = ActionA | ActionB;

function reducer(action:Action) {
    switch (action.type) {
        case 'a':
            return console.info('action a: ', action.a) 
        case 'b':
            return console.info('action b: ', action.b)          
    }
}

这篇关于如何在 TypeScript 中输入 Redux 动作和 Redux 减速器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆