2

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

1
  • You can use the Partial type, or you could use Omit and isFetching, and then include it as an optional property Commented Jun 27, 2020 at 21:17

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Because of this, I got problems with number | undefined instead of number, typeof turned out to be very bad for this task. Thanks, I writing types manually

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.