1

I have been a React dev for some time now. At work, we have now introduced Typescript which I am relatively new to.

I have created a hook for using cookies but the function I return is causing an error.

The hook (with some company stuff removed):

function useCookies(key: string) {
  const [storedCookie, setStoredCookie] = useState(() => getCookieValue(key));

  function setCookie(value: any, daysUntilExpiry?: number): any {
    if (value) {
      const valueToStore =
        value instanceof Function ? value(storedCookie) : value;
      setStoredCookie(valueToStore);

      let cookieString = `${key}=${valueToStore}`;
      if (daysUntilExpiry) {
        const date = new Date();
        date.setDate(date.getDate() + daysUntilExpiry);
        cookieString = `${cookieString}; expires=${date}`;
      }
      document.cookie = cookieString;
    }
  }

  return [storedCookie, setCookie];
}
const [loggedIn, setAuthState] = useCookies('logged_in');

setAuthState(true, 7);

The setAuthState function call gives me the error Expected an assignment or function call and instead saw an expression. Can anyone point me as to why?!

1
  • It looks like a TS bug...the return type is not resoved correctly. If you explicitly declare the return type it compiles. function useCookies(key: string): [string, (value: any, daysUntilExpiry?: number) => void] You should file this under TS github issues. Commented May 14, 2019 at 10:44

1 Answer 1

1

The return type of useCookies is inferred as an array that is any length and that can contain either strings or functions that set the cookie. Because of this, when you pluck the second item out of the list, TS thinks that this could be either a string or a function.

To fix this, if you're on 3.4+, when you return your value from your function, just mark it with as const as you return it:

return [cookie, setCookie] as const;

EDIT: Per Svensson's suggestion above also fixed it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.