在使用 Typescript 的过程中, 有些库时没有声明文件的, 如果要顺利使用这些库, 可能需要我们添加声明文件。
步骤:
1、 项目根目录下添加 index.d.ts, 并在其中写类型声明
2、 将 index.d.ts 加入到 tsconfig.json 中的配置项 include
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"experimentalDecorators": true
},
"include": [
"./src/**/*",
"./index.d.ts"
]
}
注意: index.d.ts 文件中的 import 应该在 module declaration 里面声明
举例来说:
Github 有一 fork node-ftp 的库 @icetee/ftp, @icetee/ftp 中并没有类型声明文件, 当我们引入 @icetee/ftp 时, 会有这样的错误

error-message.png
为快速使用起来, 当即 把 @types/ftp 库里的声明文件内容拷贝到 index.d.ts 里, 但是出现了问题

import-error.png
要解决这样的问题需要将 开头2行 import 的代码移动到 declare module '@icetee/ftp' 内才行

correct.png
参考内容:
Stackoverflow