简体   繁体   English

打字稿中的导出功能

[英]Export function in Typescript

I have a .ts file with a module and a function outside module like this: 我有一个带有模块的.ts文件和一个外部模块的函数,如下所示:

$(function () {
   populate()
});

function populate() {
...
}

module portfolio.charts {
   export function foo(){
   ...
   }
}

Using Typescript compiler command tsc --declaration the declaration file is created. 使用Typescript编译器命令tsc --declaration创建声明文件。 This .d.ts file contains the following code: .d.ts文件包含以下代码:

 function populate(): void;
 module portfolio.charts {
       function foo(): void;
 }

Why populate() function and portfolio.charts module are exported? 为什么要导出populate()函数和portfolio.charts模块? I thought it was necessary the keyword export to export a function or a module. 我认为关键字export必须导出函数或模块。 If I add the d.ts file as a dependency on another file I can use all functions and the module. 如果我将d.ts文件添加为另一个文件的依赖项,我可以使用所有函数和模块。 Can I declare them private? 我可以将它们声明为私人吗? Thanks and sorry for my english. 谢谢你,我的英语不好意思。

The TypeScript specification is a bit dry on this, so here are some examples. TypeScript规范有点干,所以这里有一些例子。

Example 1 例1

module MyModule {
    class MyClass {
        myFunction() {
            alert('Test');
        }
    }

    function myOtherFunction() {
        alert('Test Again');
    }
}

In this example, MyModule is a global module (it isn't inside of any other module) so this will appear in the definition file. 在此示例中, MyModule是一个全局模块(它不在任何其他模块中),因此它将出现在定义文件中。 MyClass , myFunction and myOtherFunction are invisible in the definition: MyClassmyFunctionmyOtherFunction在定义中不可见:

module MyModule {
}

So to make something visible in your declaration, it either... 所以要在你的宣言中看到一些东西,它要么......

  1. Needs to be in the global scope, like MyModule or like populate in your example, or 需要在全局范围内,例如MyModule或者像你的例子中populate ,或者

  2. Needs to be prefixed with the export keyword 需要以export关键字为前缀

In your example, point 1 applies. 在您的示例中,第1点适用。

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

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