Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to handle undefined declaration files (index.d.ts)

I got following error

error TS7016: Could not find a declaration file for module 'react-native-camera'. '/Users/ilja/Documents/Repositories/blok/node_modules/react-native-camera/index.js' implicitly has an 'any' type.
  Try `npm install @types/react-native-camera` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-native-camera';`

As a quick fix I created typings/index.d.ts (there is no @types/react-native-camera) file at root of my project and populated it with

declare module 'react-native-camera';

then, in my tsconfig file I added it to my type roots like this

"typeRoots": ["node_modules/@types", "./typings"],

however I am still getting same error when I build, leading me to think that my implementation is incorrect, what did I miss?

Edit, my full tsconfig looks like this

{
  "compilerOptions": {
    "target": "ES6",
    "module": "commonjs",
    "lib": ["es7"],
    "allowJs": true,
    "checkJs": true,
    "jsx": "react-native",
    "removeComments": true,
    "outDir": "./dist",
    "typeRoots": ["node_modules/@types", "./typings"],
    "experimentalDecorators": true,
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "allowSyntheticDefaultImports": true,
    "strict": true
  },
  "exclude": ["./node_modules", "./android", "./ios", "./assets", "./__tests__", "./dist"],
  "include": ["./src"]
}
like image 493
Ilja Avatar asked Nov 30 '17 12:11

Ilja


1 Answers

The typeRoots options specifies where to look for packages that may contain type information. The documentation keeps saying that the compiler is looking for packages.

I've reproduced the structure you described and got the same error you did. Then I created a react-native-camera under typings and moved index.d.ts there so that I end up with this structure:

typings/
└── react-native-camera
    └── index.d.ts

With this structure, the compilation runs just fine.

Using a typings directory structure is fine, if you want that kind of structure. For some projects I use a typings directory. For other projects, I prefer something simpler: a .d.ts file in the source tree that declares everything that needs declaring. So if I start from the description you give, but dump typings and instead add src/definitions.d.ts containing

declare module 'react-native-camera';

then the code compiles just fine.

It is really a matter of preference what to use. Usually when a project becomes so complex that src/definitions.d.ts ends up being difficult to manage or hard to understand, I move to using a typings directory.

like image 68
Louis Avatar answered Oct 14 '22 02:10

Louis