So basically for my use case, assume we have these functions
const fn1 = ({level, type}) => { console.log(level,type)}
const fn2 = ({level, username}) => { console.log(level,username)}
const fn3 = ({level, age}) => { console.log(level,age)}
Now I have 2 components that calling these functions,
const Component1 = () => {
const {level} = useGetUserInfo();
useEffect((fn1({level, type: 1})) => {}, [])
}
const Component2 = () => {
const {level} = useGetUserInfo();
useEffect((fn2({level, username: 'username'})) => {}, [])
useEffect((fn3({level, age: '27'})) => {}, [])
}
so as you can see, the part to get level is the same between two components, and I dont want this to happen (in reality, other than level, there is a set of common information taking from different places which making the code longer and more repeated)
So what I want to achieve is write a custom hook that take in the fn array and return the wrapper fn
So that i can write like this
const Component1 = () => {
const [returnFn1] = useWrapperFn(fn1);
useEffect((returnFn1({type: 1})) => {}, []). // --> here i dont need to pass level anymore
}
const Component2 = () => {
const [returnFn2, returnFn3] = useWrapperFn(fn2,fn3);
useEffect((returnFn2({username: 'username'})) => {}, []) // --> no need to pass in level
useEffect((returnFn3({age: '27'})) => {}, []) // --> no need to pass in level
}
so far this is my hook that appriciate your help to give feedback for fixing:
const useWrapperFn = <T extends any[]>(fns: ((...args: T) => void)[]) => {
const {level} = useGetUserInfo();
const returnFns = fns.map((fn) => {
return ((...args: any[]) => {
// @ts-ignore
fn({ ...args[0], level}); //-> here i inject the level
}) as (props: Omit<NonNullable<Parameters<typeof fn>[0]>, 'level'>) => void;
});
return returnFns;
};
export default useWrapperFn;
What I want is when i used the returnFn, it should still having correct props type checking for the remaining fields. For example when I called returnFn1 and doesnt pass in type
, TS error will be prompt.
returnFn1({type: 1}) // -> works
returnFn1() // -> will throw ts error missing type
Current behavior
Currently JS wise, the logic is correct
For TS lint check wise, it is working with Component 1 ( passing only 1 fn to array)
However, for Component2 (passing more than 1 fn), then the TS lint will be a combination of all function props
This would mean that
returnFn2({username: 'username'}) // --> currently prompt that missing `age` , wherease `age` belong to fn3
returnFn3({age: '27'}) // --> currently prompt that missing `usernamse` , wherease `username` belong to fn2
So is there anyway to modify my useWrapperFn hook, so that the returnedFn arrays it return will have correct props type