如何在 TypeScript 中导入 JavaScript 模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12771258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 16:13:28  来源:igfitidea点击:

How to import JavaScript modules in TypeScript

importtypescript

提问by Adam Tegen

I've got some JavaScript code that I'm trying to convert to Typescript.

我有一些 JavaScript 代码,我正在尝试将其转换为 Typescript。

Supposedly, typescript is a superset of JavaScript, except the following has compiler errors. Assuming I didn't import the ko library into typescript, how would I convert the following code:

据说,typescript 是 JavaScript 的超集,但以下内容存在编译器错误。假设我没有将 ko 库导入打字稿,我将如何转换以下代码:

(function(ko, viewModels){
    viewModels.MyViewModel = function(){
        //stuff in here
    }
}(ko, window.viewModels = window.viewModels || {}));

For references, this was my attempt in TypeScript

作为参考,这是我在 TypeScript 中的尝试

module viewModels {

    export class PartDetailsViewModel {
        public bar: string;
             constructor (){
                 this.bar = ko.foo(); //<-- compiler error, "ko" does not exist in current scope
             }
        }
    }
}

回答by nxn

Look into TypeScript's "Ambient Declarations" which allow you to declare external members that will be supplied at run-time. So in your example, adding the following would make the compiler happy:

查看 TypeScript 的“环境声明”,它允许您声明将在运行时提供的外部成员。因此,在您的示例中,添加以下内容将使编译器满意:

declare var ko;

By the way, I'd like to also direct you at this post: https://stackoverflow.com/a/12692174/806003

顺便说一句,我还想指导您阅读这篇文章:https: //stackoverflow.com/a/12692174/806003

Sten provided a basic knockout interface so that you can specify a type on your declaration to get some static typing on it. Also found this in the comments: https://gist.github.com/3833509

Sten 提供了一个基本的淘汰接口,以便您可以在声明中指定一个类型以在其上获得一些静态类型。在评论中也发现了这一点:https: //gist.github.com/3833509