如何在TypeScript中导入JavaScript模块 [英] How to import JavaScript modules in TypeScript

查看:1052
本文介绍了如何在TypeScript中导入JavaScript模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

据说,typescript是JavaScript的超集,除了以下有编译器错误。假设我没有将ko库导入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:

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

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

For references, this was my attempt in TypeScript

module viewModels {

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


推荐答案

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

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:

declare var ko;

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

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

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

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

这篇关于如何在TypeScript中导入JavaScript模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆