Home > database >  TypeScript: tsc failed to compile a dependant library (inside a project) which depends on a js libra
TypeScript: tsc failed to compile a dependant library (inside a project) which depends on a js libra

Time:10-21

Given a library (let's call it LibraryA) that uses another library without typing - particularly js-yaml. To do so LibraryA has a devDependency @types/js-yam in its package.json. LibraryA itself compiles just fine.

Now I have a project where I installed LibraryA as a dependency (in devDependencies). In that project I imported types from the LibraryA and so that LibraryA gets compiled by tsc when I compile the whole project. But tsc reports an error about code in LibraryA where I import js-yaml (import yaml from 'js-yaml'):

error TS7016: Could not find a declaration file for module 'js-yaml'.

I checked the node_modules for the project, and there's no @types/js-yaml there. So, it explains why tsc can't see the typings. But I can't understand why it wasn't installed in the first place (when I installed LibraryA).

project
 package.json
   devDependencies
     LibraryA

LibraryA
  package.json
    dependencies
      "js-yaml": "^4.1.0",
    devDependencies
      "@types/js-yaml": "^4.0.5",

js-yaml

So, probably the question is about npm and why it doesn't install "@types/js-yaml inside the project.

CodePudding user response:

Because it is a different package, per se. I think it doesn't install automatically because @types is an organisation in npm, and not all npm packages explicitly list @types/package-name as a dependency, particularly if is has custom types.

TypeScript typings in npm @types org packages

CodePudding user response:

"@types/js-yaml" is listed as a dev dependency. These are only installed during the development of the library for the developers to use. Usually, this includes testing frameworks, bundlers, and of course, TypeScript types. However, this doesn't mean that when you install the library, it should also install these dev dependencies. Why would you need or even care about what the authors used to write the library?

Also, your package manager doesn't read your mind; it won't install packages for you unless you explicitly tell it to do so. Here, you should probably explicitly install js-yaml and @types/js-yaml as a dev dependency yourself.

And another reason why it shouldn't install the library's @types/js-yaml: if the versions of the js-yaml you want to use and the js-yaml the library uses, you might have conflicting types! That's really annoying when trying to develop something (wrong autocomplete/suggestions, things that don't exist at runtime, etc).

  • Related