Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhanced useFastContextFields Function #14

Open
owaisahmed5300 opened this issue Sep 12, 2024 · 0 comments
Open

Enhanced useFastContextFields Function #14

owaisahmed5300 opened this issue Sep 12, 2024 · 0 comments

Comments

@owaisahmed5300
Copy link

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant