In a basic React custom hook in which the only difference is returning with [ ]
or { }
:
const useCustomHookSquare= () => {
const [state, setState] = useState<Type>(initialState);
return [state, storeBounceBox];
}
const useCustomHookCurly= () => {
const [state, setState] = useState<Type>(initialState);
return {state, storeBounceBox};
}
This works:
const {state, setState} = useCustomHookCurly();
// or even
const {setState} = useCustomHookCurly();
But doing the exact same thing deconstructing with square brackets gives me a TypeScript error when calling the setState function (or any other function exported this way):
const [state, setState] = useCustomHookSquare();
setState(someState); // "This expression is not callable. Type has no call signatures".
I feel like there is some basic JavaScript concept I'm missing here. Why does the {}
version allow me to call the function but the []
version doesn't?
Because your
useCustomHookSquare
hook has no return type information TypeScript infers that it returns an array of two different types. But not both of the types that can be part of that array are functions, so you get a type error because one of the possible values isn't callable.Add some return types to your
useCustomHookSquare
function to fix the problem. Here's what my fixed example would look like.TypeScript now understands that the returned array only has 2 items in it, and those items types should always be the same.