How to type Redux actions and Redux reducers in TypeScript?

后端 未结 20 2057
旧时难觅i
旧时难觅i 2020-12-13 03:39

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

20条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 04:21

    you could do the following things

    if you expect one of IActionA or IActionB only, you can limit the type at least and define your function as

    const reducer = (action: (IActionA | IActionB)) => {
       ...
    }
    

    Now, the thing is, you still have to find out which type it is. You can totally add a type property but then, you have to set it somewhere, and interfaces are only overlays over object structures. You could create action classes and have the ctor set the type.

    Otherwise you have to verify the object by something else. In your case you could use hasOwnProperty and depending on that, cast it to the correct type:

    const reducer = (action: (IActionA | IActionB)) => {
        if(action.hasOwnProperty("a")){
            return (action).a;
        }
    
        return (action).b;
    }
    

    This would still work when compiled to JavaScript.

提交回复
热议问题