Strange TypeScript errors: When a data type is not assignable to itself

During the last few months, when I developed a Babel plugin with TypeScript, I encountered strange errors like the following several times:

src/plugin/visitors/flow.ts:59:22 - error TS2345: Argument of type 'TSTypeAliasDeclaration' is not assignable to parameter of type 'AnyTypeAnnotation | ArgumentPlaceholder | ... 222 more ... | NodePath<...>'.
  Type 'import("<path>/node_modules/@babel/types/lib/index").TSTypeAliasDeclaration' is not assignable to type 'babel.types.TSTypeAliasDeclaration'.

59     path.replaceWith(convertDeclareOpaqueType(node, state));

At first sight, these look like the same data types and it should be no problem to assign them to each other. Of course TSTypeAliasDeclaration from @babel/types should be assignable to TSTypeAliasDeclaration! However, TypeScript disagrees. It took me a while to figure out what is wrong.

The problem: npm version mismatches

Recently I read in the React documentation that several versions of React can break the new Hooks feature. That put me on the right track. After executing the following command, it became clear where the source of the problem was.

npm ls @babel/types

One of the dependencies set a different version range of @babel/types. This was enough to convince TypeScript that the types were incompatible (I am still not sure if they were). Thankfully, Yarn offers a feature to resolve such conflicts called selective version resolutions. This way you can force that all installed npm packages must use a specific version of another dependency. Simply add the following to your package.json to activate this feature:

// package.json
  "resolutions": {
    "@babel/types": "^7.5.0"

Another pitfall: Yarn’s cache

A further problem can be the Yarn cache. When installing npm packages with Yarn they are retrieved from its cache first. So if there are still “bad” versions in the cache, problems like the ones above can occur.

Execute the following to purge the Yarn cache completely:

yarn cache clean

Delete your node_modules/ directory afterward and reinstall the packages.