Posts tagged "returntype"

Enhance Redux props with ReturnType

The following example is built in the offical Redux documentation:

import { AppState } from './store'

import { SystemState } from './store/system/types'

import { ChatState } from './store/chat/types'

interface AppProps {
  chat: ChatState
  system: SystemState
}

const mapStateToProps = (state: AppState) => ({
  system: state.system,
  chat: state.chat
})

Here, SystemState and ChatState are imported and used manually.

But as AppState is correctly typed, we can use our beloved ReturnType instead:

import { AppState } from './store'

type AppProps = ReturnType<typeof mapStateToProps>

const mapStateToProps = (state: AppState) => ({
  system: state.system,
  chat: state.chat
})

Check out this CodeSandbox for a runnning example.


Typescript ReturnType

Typescript includes several useful utility types to enhance the type declarations of your code-base.

The ReturnType function is one of my favorite ones, as it helps reduce type definition duplication.

Suppose you have the following function definition:

type IsInText = (
  text: string
) => (
  term: string,
  minCount: number,
  maxCount?: number,
  caseSensitive?: boolean
) => boolean

Now we want to write a function allTermsInText, that takes the function returned by isInText as an argument. It should be used like:

allTermsInText(["Typescript", "awesome"], isInText("Typescript is awesome!"))

Here is the definition without the utility type:

type AllTermsInText = (
  terms: string[],
  search: (
    term: string,
    minCount: number,
    maxCount?: number,
    caseSensitive?: boolean
  ) => boolean
) => boolean

And here the same function definition, but using ReturnType for the parameters:

let AllTermsInText = (terms: string[], search: ReturnType<IsInText>) => {
  return !terms.find(term => !search(term, 1))
}