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

查看:55
本文介绍了为什么 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 关键字,后者在方法级别使用来表示方法或属性应该可以从外部访问.那么为什么不使用相同的机制来使类和接口等在外部可见呢?

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 的计划.您可能会争辩说他们应该使用export"而不是public",但除了export/private/protected"是一组匹配不佳的访问修饰符之外,我相信两者之间存在细微的差异,可以解释这一点.

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天全站免登陆