Search code examples
reactjscookiesjquery-cookiejs-cookiereact-cookie

Type error: Property 'get' does not exist on type 'typeof import("js-cookie")'


I'm unable to build the following JS react code:

import Cookies from 'js-cookie';

React.useEffect(() => {
  
  interface UserInfo {
  name: string;
  verified: boolean;
}
  
  const userInfo = Cookies.get('userInfo');
  if (userInfo && !userInfo.verified) {
    setUserName(`unknown`);
  } else {
    setUserName('else');
  }
}, []);

Getting:

Type error: Property 'get' does not exist on type 'typeof import("js-cookie")'.

87 | const userInfo = Cookies.get('userInfo');

I tried: npm install js-cookie npm install --save @types/js-cookie

but still getting the error, any idea why?


Solution

  • Looking through the type definitions for js-cookie I found an odd bit of syntax: export = Cookies.

    We're far away from an export default Cookies.

    So why this syntax? Well according to this (still open) issue on Typescript Github it means the module was authored using Node's CommonJS syntax (i.e. require and module.exports) but here's the catch, js-cookie (at least on its main branch) is authored using good old ES6 modules using the .mjs extension, and it does use an export default statement.

    So what happened? It could be one of the following:

    • Previous versions weren't written using modules and the type definitions have not been updated since
    • Their rollup config does something very strange in its bundling

    My potential fixes (sorted from preferred to least preferred):

    • Use import * as Cookies from "js-cookie" and see if it functions properly
    • Use import { default as Cookies } from "js-cookie" and see if it functions properly
    • Use the ugly but apparently valid syntax of import Cookies = require("js-cookie")

    If none function properly in your app, then we'll need to dig into TS usage of js-cookie to find what works for them