为什么Typescript使用关键字"export"?使类和接口公开? [英] Why does Typescript use the keyword "export" to make classes and interfaces public?

查看:239
本文介绍了为什么Typescript使用关键字"export"?使类和接口公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用Typescript时,我意识到模块中的类(用作名称空间)对于其他类是不可用的,除非我在它们之前写了export关键字,例如:

While dabbling with Typescript I realised my classes within modules (used as namespaces) were not available to other classes unless I wrote the export keyword before them, such as:

module some.namespace.here
{
   export class SomeClass{..}
}

所以现在我可以像上面这样使用上面的代码:

So now I can use the above code like this:

var someVar = new some.namespace.here.SomeClass();

但是,我只是想知道为什么使用此关键字,而不是仅仅使用public关键字,而在方法级别使用public关键字表示应该从外部访问方法或属性.那么,为什么不使用这种相同的机制使类和接口等在外部可见呢?

However I was just wondering why this keyword is used opposed to just using the public keyword which is used at method level to signify that a method or property should be externally accessible. So why not just use this same mechanism to make classes and interfaces etc externally visible?

这将给出结果代码,例如:

This would give resulting code like:

module some.namespace.here
{
   public class SomeClass{..}
}

推荐答案

主要原因是export与ECMAScript的计划匹配.您可能会争辩说他们应该使用导出"而不是公共",但是导出/私有/受保护"的辅助功能是一组访问修饰符不匹配的,我认为两者之间存在细微的差异,这可以解释这一点.

The primary reason is that export matches the plans for ECMAScript. You could argue that "they should have used "export" instead of "public", but asides from "export/private/protected" being a poorly matched set of access modifiers, I believe there is a subtle difference between the two that explains this.

在TypeScript中,将类成员标记为publicprivate对生成的JavaScript无效.它只是一个设计/编译时工具,您可以使用它来阻止TypeScript代码访问它不应该访问的内容.

In TypeScript, marking a class member as public or private has no effect on the generated JavaScript. It is simply a design / compile time tool that you can use to stop your TypeScript code accessing things it shouldn't.

使用export关键字,JavaScript添加一行以将导出的项目添加到模块.在您的示例中:here.SomeClass = SomeClass;.

With the export keyword, the JavaScript adds a line to add the exported item to the module. In your example: here.SomeClass = SomeClass;.

因此,从概念上讲,由publicprivate控制的可见性仅用于工具,而export关键字更改输出.

So conceptually, visibility as controlled by public and private is just for tooling, whereas the export keyword changes the output.

这篇关于为什么Typescript使用关键字"export"?使类和接口公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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