'how to get return type of map & only give S

how to get return type of map & only give S.
how to get return type of map & only give S.
how to get return type of map & only give S.
how to get return type of map & only give S.
how to get return type of map & only give S.


const state = {
  a: 1,
  b: 2
}

type StateValue = typeof state

type Getter<S, R, R1> = {
  map: (state: S) => R
  mapB?: (state: S) => R1
  // more ...
}

function getter<S extends Getter<any, any, any>>(
  a: S
): ReturnType<S['map']> & ReturnType<S['mapB']> {
  return {
    ...a.map(state),
    ...a.mapB?.(state)
    // more ...
  }
}

// to much type
const v = getter({
  map: (state: StateValue) => ({
    a: state.a
  }),
  mapB: (state: StateValue) => ({
    b: state.b
  })
  // more map ...
})

// want!! // state will be <{ a: 1, b: 2, c: 1 }>
const v = getter<StateValue>({
  map: (state) => ({
    a: state.a,
    c: state.a
  }),
  mapB: (state) => ({
    b: state.b
  })
})


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source