fast-react-context
fast-react-context copied to clipboard
Enhanced useFastContextFields Function
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;
}