About
This article explains to you how typescript or your ide will search for type declaration files.
At the end of this article, you should be able to resolve this kind of error:
TS2307: Cannot find module 'name' or its corresponding type declarations.
How it works?
For local libraries
When you are creating your own library, typescript will check your package.json 1)
The resolution is:
- First check the optional types field in
- Then the “main” field,
- and finally will try index.d.ts in the root.
Package.json | Location of default .d.ts |
---|---|
No “types” field | checks “main”, then index.d.ts |
“types”: “main.d.ts” | main.d.ts |
“types”: “./dist/main.js” or “./dist/main.d.ts” | ./dist/main.d.ts |
If absent, then “main” is used
Package.json | Location of default .d.ts |
---|---|
No “main” field | index.d.ts |
“main”:“index.js” | index.d.ts |
“main”:“./dist/index.js” | ./dist/index.d.ts |
For dependency libraries
In case of dependency or external libraries, if the library is not shipping the type declaration files, you can always try to find and install a typings package.
This is a package that ships only the type declaration files. They are generally created by a third party.
Example for the lodash library
yarn add @types/lodash --dev
// or
npm install -S @types/lodash