Search code examples
typescriptnpmtypescript-typings

NPM package cannot be used as a JSX Component - Type errors


Ive been getting these strange type errors on my typescript project for certain packages. Ex:

'TimeAgo' cannot be used as a JSX component.
  Its instance type 'ReactTimeago<keyof IntrinsicElements | ComponentType<{}>>' is not a valid JSX element.
    The types returned by 'render()' are incompatible between these types.
      Type 'React.ReactNode' is not assignable to type 'import("/home/user/app/node_modules/@types/react-bootstrap-table-next/node_modules/@types/react/index").ReactNode'.
        Type '{}' is not assignable to type 'ReactNode'.

I don't get these type errors on my local windows machine but they keep occurring in my linux virtual machine. I've deleted the project many times, cloned my repo and installed packages again in different versions of node and I still get the same type errors.

Checked node 12.18.3, 16.13.1

Here is some quick package json info:

"react-timeago": "^6.2.1",
"react-custom-scrollbars": "^4.2.1",
"react-custom-scrollbars-2": "^4.4.0",
"react": "^17.0.2",
"next": "^12.1.1",
"@types/react-custom-scrollbars": "^4.0.10",
"@types/react-timeago": "^4.1.3",
"@types/react": "^17.0.44",
"typescript": "^4.3.5"
"@types/node": "^14.18.12",

This happens on basic custom components:

MyTst.tsx
import TimeAgo from "react-timeago";

const Mytst = () => {
  return (
    <div>
      <TimeAgo date={"02/02/2022"} />
    </div>
  );
};

export default Mytst;

I get this error for react-custom-scrollbars-2 as well. There seems to be an issue with matching the types correctly between the library which contains the component and the @types files associated with them. Anyone have any ideas on how to resolve these type errors?


Solution

  • Had the same issue. Just add this:

    "resolutions": {
      "@types/react": "17.0.2",
      "@types/react-dom": "17.0.2"
    },
    

    to the package.json file and run yarn command.

    UPD: Just a bit detailed answer:

    @types/react-dom has its own dependencies and one of them is @types/react with a version set to '*' - a major release, that now, probably refers to 18.

    Even if you specify some strict versions in your package.json (without ^), parent package might install its own duplicates of packages that you are already using for its own purpose.

    By using resolutions, we are specifying strict restrictions for dependencies of dependencies.