Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript React Hooks, custom hook type inference issue

So I have this custom hook to decode a token

export function useToken(initial: string) {
  const [token, setToken] = useState<string>(initial)
  const [decoded, setDecoded] = useState<Token>()

  useEffect(() => {
    if (token) {
      const value = decodeToken(token)
      if (isTokenExpired(value)) {
        setDecoded(undefined)
      } else {
        setDecoded(value)
      }
    } else {
      setDecoded(undefined)
    }
  }, [token])

  return [decoded, setToken]
}

The return type looks good, here a

[Token, React.Dispatch<React.SetStateAction<string>>]

I have another hook that uses this hook, but it's seeing the return type incorrectly

export function useUser() {
  const [decoded, setToken] = useToken(getTokenFromStorage())
  //...

Here useToken gives both decoded and setToken the same type of

Token | React.Dispatch<React.SetStateAction<string>>

i.e.

decoded: Token | React.Dispatch<React.SetStateAction<string>>, setToken: Token | React.Dispatch<React.SetStateAction<string>>

What am I doing wrong...

like image 758
Tim Avatar asked Oct 15 '25 05:10

Tim


2 Answers

I got the same issue the other day!

You have to be explicit with the return type, as Typescript isn't inferring the type correctly.

For example:

export function useToken(initial: string): [Token, React.Dispatch<React.SetStateAction<string>>] {
}

That should fix it... I think it is a typescript bug so probably an issue needs to be made for it.

like image 127
FabianCook Avatar answered Oct 18 '25 10:10

FabianCook


You may try to use "as const" at the end of the return. This is resolve issue.

return [decoded, setToken] as const

for more info check "const assertions"

like image 31
Arun kumar Avatar answered Oct 18 '25 08:10

Arun kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!