网站搜索

javascript - 为外部库文件创建 .d.ts 以供项目使用


我有一个闭源的纯 JS 库,它将通过指向 CDN 的 <script> 标签引入。我想为这个库编写自己的类型定义文件,以便在库加载到 HTML 页面后引用它提供的全局对象。

到目前为止,我在让我的 IDE 显示它识别 .d.ts 文件方面遇到了麻烦。

我有以下项目结构:

project-folder/
 - tsconfig.json
 - src/
definitions/
- mylibrary.d.ts

在 tsconfig 中,我有以下内容:

{
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "typeRoots": ["../definitions/"]
  },
  "include": ["./src"]
}

在 mylibrary.d.ts 中,我有以下内容:

interface example {
  hello: boolean;
}

declare namespace MyLibraryObject {
    const testing: string; 
    function foo(bar: string): void;
}

然后在 main.ts 中,我尝试使用 d.ts 文件中定义的任何类型,例如:

const test: example = { hello: true };

console.log(MyLibraryObject.testing);
MyLibaryObject.foo();

但是 TS 无法找到这些的定义,如下所示:

我可以做些什么来解决这个问题?

答案#1

我弄明白了,解决方法是在 tsconfig 文件中扩大“包含”的路径集合。

{
  "compilerOptions": {
    ...
    "typeRoots": ["../definitions/"]
  },
  "include": ["./src", "../definitions/"]
}