Ericgit
Ericgit

Reputation: 7103

Expected 1 arguments, but got 0

I created my custom hook in react using TypeScript, but I'm getting the below error, and I don't have any Idea about this:

const getMode: (mode: any) => any
Expected 1 arguments, but got 0.ts(2554)
DarkModeStatus.tsx(2, 20): An argument for 'mode' was not provided.

The method(func) I'm using here is not getting any parameter, when I invoke the getMode() I'm getting the above message.

This my custom hook Code:

export const useDarkModeStatus = () => {
  const setMode = (mode): void => {
    console.log(mode, " setMode")
    typeof window !== "undefined" &&
      window.localStorage.setItem("theme", JSON.stringify(mode))
  }

  const getMode = () =>
    typeof window !== "undefined" &&
    JSON.parse(window.localStorage.getItem("theme"))
  return [getMode, setMode]
}

There I've invoked my function:

import { useDarkModeStatus } from "../components/DarkModeStatus/DarkModeStatus"
 const [getMode] = useDarkModeStatus()
 useEffect(() => {
    const value = getMode()
    dispatch({ type: "INITIAL_MODE", value })
  }, [])

When I pass an argument to getMode('yes') the error is solved even I'm not receiving any parameter, thanks!

Upvotes: 1

Views: 9842

Answers (1)

zerkms
zerkms

Reputation: 255115

The compiler tries to infer the type to be not too wide, and not to narrow to fit all the members.

With the details you provided (no at all) the inferred type for the returned result would be:

(() => any | (any) => void)[]

Given that, the first item of the value returned by this function is () => any | (any) => void. Which you cannot invoke without arguments.

To fix it you must either declare the returned type of the useDarkModeStatus explicitly, or put as const:

return [getMode, setMode] as const;

That way TS uses the most specific type possible: a tuple of 2 elements with every item having as specific type as possible.

Upvotes: 2

Related Questions