简体   繁体   English

Angular 5:向外部 JS 文件添加类型

[英]Angular 5: adding types to external JS file

I'm loading a JS file through a <script src="http://.../script.js">我正在通过<script src="http://.../script.js">加载一个 JS 文件

In the JS, there is a namespace "foo", and a method "bar".在 JS 中,有一个命名空间“foo”和一个方法“bar”。

I would like to call foo.bar() from my component.我想从我的组件中调用foo.bar()

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.我有带有类型定义的文件script.d.ts 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.我不知道如何在 Angular 构建中包含这个文件(使用 CLI),以便在构建过程中进行类型检查,但在运行时,外部 JS 文件中的命名空间和函数将从我的组件中调用。 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 :您不需要导出修饰符,因为它们不是从模块导出的,您可以使用declare并使用///引用它们,或者在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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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