javascript - 本地 JS 文件的 Typescript 声明文件
问题描述
在我们转换为 Typescript 的过程中,我正在尝试为我们的 Javascript 文件添加类型。但是,我无法识别声明文件。
这是我的文件结构
- js
- Foo.js
- 打字
- 富
- 索引.d.ts
- 富
- 索引.ts
- 包.json
- tsconfig.json
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.
解决方案
为相对导入提供声明的唯一方法'./js/Foo'
是在导入路径(加号.d.ts
或 在这种情况下, /都不会起作用: /只影响“非相对”路径的模块解析,并且可以用于让 TypeScript 加载文件,但根本不影响导入路径和文件之间的关系。/index.d.ts
rootDirs
typeRoots
baseUrl
paths
baseUrl
paths
typeRoots
最简单的解决方案是将Foo.d.ts
文件放在与Foo.js
. 如果您想将类型保存在单独的目录中,则可以添加"rootDirs": ["js", "typings"]
到tsconfig.json
. 该更改足以使您的示例对我有用,尽管我发现拥有相应的Foo.js
和Foo/index.d.ts
文件令人困惑,并鼓励您在使用子目录时保持一致,即切换到Foo/index.js
JavaScript 端或切换到Foo.d.ts
TypeScript边。
推荐阅读
- azureservicebus - “message.DeliveryCount”引发了“System.InvalidOperationException”类型的异常
- random - Jmeter:测试脚本中的 24 位随机数
- python - 如何忽略用户未通过 SQLITE 的条件?
- json - 如何从具有值 {[]} 的 Jarray 中获取 []
- python - 无法使用 conda install 或 pip 安装 scanpy 包
- javascript - 如何解构对象中的数组并重命名从中创建的变量?
- javascript - tippy.js 工具提示不响应 CSS 样式
- puppet - Puppet:将文件内容加载到变量(特别是哈希变量)
- python - 无法在输出中添加“/”
- spark-streaming - 火花流检查点占用多少空间?