首页 > 解决方案 > 本地 JS 文件的 Typescript 声明文件

问题描述

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

这是我的文件结构

Foo.js

module.exports = function Foo() {
   return 'Bar';
 };

索引.d.ts

export = Foo;

declare function Foo(): string;

索引.ts

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

console.log(Foo());

tsconfig.json

{
  "compilerOptions": {
    "typeRoots": ["./typings"],
    "target": "es5",
    "strict": true,
    "baseUrl": "./",
    "paths": {
      "*": ["typings/*"]
    }
  }
}

包.json

{
  "name": "fail",
  "version": "1.0.0",
  "description": "",
  "main": "index.ts",
  "scripts": {
    "tsc": "tsc"
  },
  "author": "",
  "license": "MIT",
  "dependencies": {
    "typescript": "^3.1.4"
  }
}

这是重现我的问题的回购

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.

标签: javascripttypescriptdeclarationtype-declarationdeclaration-files

解决方案


为相对导入提供声明的唯一方法'./js/Foo'是在导入路径(加号.d.ts或 在这种情况下, /都不会起作用: /只影响“非相对”路径的模块解析,并且可以用于让 TypeScript 加载文件,但根本不影响导入路径和文件之间的关系。/index.d.tsrootDirstypeRootsbaseUrlpathsbaseUrlpathstypeRoots

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


推荐阅读