How to type Redux actions and Redux reducers in TypeScript?

后端 未结 20 2018
旧时难觅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条回答
  •  Happy的楠姐
    2020-12-13 04:18

    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)          
        }
    }
    

提交回复
热议问题