Typescript - re-using imported types to ensure syncing

·

1 min read

Imagine you have a React component that has imported a type.

In this case it is an action type for interaction with Redux.

import myAction from '../actions'
import MyActionPayload from '.../types'

within our component where we define the const mapDispatchToProps we can re-use the imported type, this not only makes the code easier to read, but also ensure that if the imported type changes, so will the type within the const

so that instead of this

const mapDispatchToProps = (dispatch: Dispatch) => ({
                    myAction: (myActionPayload: MyActionPayload) => dispatch(myAction(myActionPayload)
})

we can use this;

const mapDispatchToProps = (dispatch: Dispatch) => ({
                    myAction: typeof myAction
})

Also then we no longer need to import MyActionPayload as that has already been taken care of in the file where myAction was defined.