0
votes

I am having problem understanding the below code from redux-form

export type DataSelector<FormData = {}, State = {}> = (formName: string, getFormState?: GetFormState) => (state: State) => FormData;

export const getFormValues: DataSelector;

// mapState
const values = getFormValues("formName")(state) // {}
return { form: values }


The IDE is giving me error that values is returning {}. Which is expected because State = {}. However, I want to use the access the values.name. Is there a way to pass in FormData or State?

1
More code. I can't run these code. - Phat Huynh
FormData = {} means it will be an empty object. You can update your type to FormData = { name: string } - Rajesh
@Rajesh but it's 3rd party library (redux-form), how can I update it? - Cloud Soh Jun Fu

1 Answers

1
votes

const getFormValues: DataSelector always sets the default type {} for the generic type parameters FormData and State, as the function does not forward those parameters to consumers.

The usual way to solve a type issue involving a third party library is: If you can't control it, wrap it. Meaning, define your own function which wraps the libary function and narrows to the desired project types.

// your own types
type MyFormData = { baz: string };
type MyState = {foo: number};

function getFormValuesWrapper(state: MyState): MyFormData {
  return getFormValues("formName")(state) as MyFormData;
}

// or keep it generic
function getFormValuesWrapper2<FormData, State>(state: State){
  return getFormValues("formName")(state) as FormData
}

const values = getFormValuesWrapper(state);
values.baz // (property) baz: string

Playground