fast-react-context icon indicating copy to clipboard operation
fast-react-context copied to clipboard

Enhanced useFastContextFields Function

Open owaisahmed5300 opened this issue 5 months ago • 0 comments

To enhance the getter type based on the actual values in FastContext, we can leverage TypeScript’s ability to infer the types of values from FastContext rather than using the more generic SelectorOutput type. This way, each field in FastContext will automatically have the correct type for its corresponding getter.

function useFastContextFields<K extends keyof FastContext>(
  fieldNames: K[]
): { [key in K]: { get: FastContext[key]; set: (value: FastContext[key]) => void } } {

  type GettersAndSettersType = { [key in K]: { get: FastContext[key]; set: (value: FastContext[key]) => void } };

  const gettersAndSetters: GettersAndSettersType = {} as GettersAndSettersType;

  for (const fieldName of fieldNames) {
    // The getter's return type is inferred directly from FastContext
    const [getter, setter] = useFastContext((fc) => fc[fieldName]);

    gettersAndSetters[fieldName] = {
      get: getter,
      set: (value: FastContext[keyof FastContext]) => setter({ [fieldName]: value } as Partial<FastContext>),
    };
  }

  return gettersAndSetters;
}

owaisahmed5300 avatar Sep 12 '24 06:09 owaisahmed5300