Skip to content

Enhanced useFastContextFields Function #14

Open
@owaisahmed5300

Description

@owaisahmed5300

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;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions