Extracting types from object properties when they are functions

Viewed 60

Hello I am trying to extract the properties of an object like this:

const combinedReducers = {
    markers: markersReducer, // () => MarkType
    mapCenter: setMapCenter // () => CenterType
}

The problem is I don't want to do it individually per property. And second issue is that the properties are functions that return something, and I want the type of that. It would be something like this

interface Props {
    markers: MarkType,
    center: CenterType
}

Is this even possible? Thank You.

1 Answers

Sure, you can do it:

const markersReducer = () => 'hello'
const setMapCenter = () => 42

const combinedReducers = {
  markers: markersReducer, // () => MarkType
  mapCenter: setMapCenter // () => CenterType
}

type Fn = (...args: any) => any

type Props<Obj extends Record<string, Fn>> = {
  [Prop in keyof Obj]: ReturnType<Obj[Prop]>
}

type Result = Props<typeof combinedReducers>

Playground

ReturnType docs

Related