Luis Aceituno
Luis Aceituno

Reputation: 939

Angular 5: adding types to external JS file

I'm loading a JS file through a <script src="http://.../script.js">

In the JS, there is a namespace "foo", and a method "bar".

I would like to call foo.bar() from my component.

I'd like to add type definitions so that I know what I'm doing while I'm coding. I have the file script.d.ts with type definitions. It looks like this:

export as namespace foo;

export namespace Baz {
    interface Qux {
    // ...
    }
}

export function bar(): Baz.Qux;

I can't figure out how to include this file in the Angular build (using CLI), so that I get type checks during build, but at runtime the namespace and function in the external JS file will be called from my component. Help?

Upvotes: 1

Views: 1076

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249506

You don't need the export modifier, since these are not exported from a module you can use declare and reference them with a /// or include the definitions in tsconfig:

// script.d.ts
declare namespace foo {
    namespace Baz {
        interface Qux {
        // ...
        }
    }

    declare function bar(): Baz.Qux;
}

// Other file
/// <reference path="./script.d.ts" />
foo.bar() // works and calls method from remote JS file

Upvotes: 1

Related Questions