如何在TypeScript中导入JavaScript模块

Ada*_*gen 3 import typescript

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

据说,typescript是JavaScript的超集,除了下面的编译器错误.假设我没有将ko库导入typescript,我将如何转换以下代码:

(function(ko, viewModels){
    viewModels.MyViewModel = function(){
        //stuff in here
    }
}(ko, window.viewModels = window.viewModels || {}));
Run Code Online (Sandbox Code Playgroud)

对于参考,这是我在TypeScript中的尝试

module viewModels {

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

nxn*_*nxn 8

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

declare var ko;
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我也想在这篇文章中指导你:https://stackoverflow.com/a/12692174/806003

Sten提供了一个基本的淘汰界面,以便您可以在声明上指定一个类型,以便在其上进行静态输入.在评论中也发现了这一点:https://gist.github.com/3833509