本地JS文件的打字稿声明文件

eri*_*n20 5 javascript declaration type-declaration typescript declaration-files

我正在尝试在转换为Typescript的过程中为我们的Javascript文件添加类型。但是,我无法识别声明文件。

这是我的文件结构

  • js
    • Foo.js
  • 打字
    • oo
      • 索引
  • 索引
  • package.json
  • tsconfig.json

Foo.js

module.exports = function Foo() {
   return 'Bar';
 };
Run Code Online (Sandbox Code Playgroud)

索引

export = Foo;

declare function Foo(): string;
Run Code Online (Sandbox Code Playgroud)

索引

import Foo = require('./js/Foo')

console.log(Foo());
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "typeRoots": ["./typings"],
    "target": "es5",
    "strict": true,
    "baseUrl": "./",
    "paths": {
      "*": ["typings/*"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

package.json

{
  "name": "fail",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "tsc": "tsc"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "typescript": "^3.1.4"
  }
}
Run Code Online (Sandbox Code Playgroud)

这是重现我的问题的回购

https://github.com/erisman20/typings_help

编辑:这是我得到的错误

error TS7016: Could not find a declaration file for module './js/Foo.js'. '....../js/Foo.js' implicitly has an 'any' type.

Mat*_*hen 5

提供相对导入声明的唯一方法'./js/Foo'是根据您的选择将声明文件实际位于导入路径(加号.d.ts/index.d.ts),或者实际上将其置于导入路径rootDirs。既不typeRoots也不baseUrl/ paths进场在这种情况下:baseUrl/ paths只会影响“非亲属”路径模块的分辨率,并且typeRoots可以用来获得打字稿负载文件,但不影响输入的路径和文件在所有的关系。

最简单的解决方案是将Foo.d.ts文件放在与相同的目录中Foo.js。如果要将输入内容保存在单独的目录中,则可以添加"rootDirs": ["js", "typings"]tsconfig.json。所做的更改足以使您的示例对我有用,尽管我发现拥有相应的Foo.jsFoo/index.d.ts文件会令人困惑,并且会鼓励您在使用子目录时保持一致,即,要么切换到Foo/index.jsJavaScript一边,要么切换到Foo.d.tsTypeScript。侧。