处理未定义声明文件的正确方法(index.d.ts)

Ilj*_*lja 10 node-modules typescript reactjs react-native typescript-typings

我收到了以下错误

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';`
Run Code Online (Sandbox Code Playgroud)

作为我在typings/index.d.ts项目根目录创建的快速修复程序(没有@ types/react-native-camera)文件并填充它

declare module 'react-native-camera';
Run Code Online (Sandbox Code Playgroud)

然后,在我的tsconfig文件中,我将它添加到我的类型根源中

"typeRoots": ["node_modules/@types", "./typings"],
Run Code Online (Sandbox Code Playgroud)

但是当我构建时我仍然遇到同样的错误,导致我认为我的实现不正确,我错过了什么?

编辑,我的完整tsconfig看起来像这样

{
  "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"]
}
Run Code Online (Sandbox Code Playgroud)

Lou*_*uis 6

typeRoots选项指定到哪里寻找可能包含类型信息.该文件口口声声说编译器正在寻找.

我已经复制了你描述的结构并且遇到了同样的错误.然后我创建了一个react-native-cameraunder typings并移动到index.d.ts那里,以便我最终得到这个结构:

typings/
??? react-native-camera
    ??? index.d.ts
Run Code Online (Sandbox Code Playgroud)

使用这种结构,编译运行得很好.

typings如果你想要那种结构,使用目录结构很好.对于某些项目,我使用typings目录.对于其他项目,我更喜欢更简单的东西:.d.ts源代码树中的一个文件,用于声明需要声明的所有内容.因此,如果我从您给出的描述开始,但转储typings并改为添加src/definitions.d.ts包含

declare module 'react-native-camera';
Run Code Online (Sandbox Code Playgroud)

然后代码编译得很好.

这是一个优先使用的问题.通常当项目变得如此复杂以至于src/definitions.d.ts难以管理或难以理解时,我会转向使用typings目录.