Reputation: 33
I have a code User.container.:
const mapState = (state: AppStateType) => ({
users: getUsers(state),
pageSize: getPageSize(state),
isFetching: getIsFetching(state)
})
const mapDispatch = {
toggleFollowingInProgress,
}
const connector = connect(mapState, mapDispatch)
type PropsFromRedux = ConnectedProps<typeof connector>
export type PropsType = PropsFromRedux & {
onPageChanged?: (page: number) => void
}
in file Users.tsx i make this:
import { PropsType } from './Users.container'
const Users = (props: PropsType) => {
...
}
The variable isFetching is not required for Users.tsx. But the compiler throws an error because i can not through ? make mapState isFetching optional.
What to do? I need to get rid of code duplication
Upvotes: 2
Views: 1425
Reputation: 5345
You have a few options. You could make that property optional itself. But if you want isFetching
to be required in the original context you could make another a separate type. I tend to create my types via type
or interface
rather than rely on the typeof
operator.
That being said, Typescript created Utility Types
.
TypeScript provides several utility types to facilitate common type transformations. These utilities are available globally.
Partial
is a Utility Type
for the purpose of:
Constructs a type with all properties of T set to optional. This utility will return a type that represents all subsets of a given type.
So you could write
const Users = (props: Partial<PropsType>) => {
Just keep in mind that will make all the properties optional, not just isFetching
.
Upvotes: 4