Search code examples
reactjstypescriptreduxredux-form

Generic type in Typescript


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?


Solution

  • 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