'make .d.ts for external library file available for project

I have a closed-source plain JS library that will be included via a <script> tag pointing to a CDN. I would like to author my own type definition file for this library so I can reference a global object that the library provides once loaded into the HTML page.

So far I am having trouble getting my IDE to show me that it recognizes the .d.ts file.

I have the following project structure:

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

In tsconfig I have the following:

{
  "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"]
}

In mylibrary.d.ts I have the following:

interface example {
  hello: boolean;
}

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

Then in main.ts I attempt to use any of the types defined in the d.ts file such as:

const test: example = { hello: true };

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

But TS cannot find the definitions for these, as seen here:

screenshot of TS errors in vscode

What can I do to resolve this?



Solution 1:[1]

I figured it out, the solution was to expand the set of "included" paths in the tsconfig file.

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 WillD