简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM