为什么某些Typescript模块名称以字符串形式给出? [英] Why are some Typescript module names given as strings?

查看:98
本文介绍了为什么某些Typescript模块名称以字符串形式给出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,Typescript模块的声明类似于

Typically, Typescript modules are declared like

declare module MyModule {
     ....
}

但有时我也会看到

declare module "MyModule" {
     ....
}

我想知道以字符串形式给出名称的目的是什么?

I am wondering what is the purpose of giving the name as a string?

我检查了打字稿文档并找到

这是其导入实体为可调用函数的模块的常用模式

This is a common pattern for modules whose imported entities are callable functions

我尝试同时编译MyModule"MyModule",它们都编译为同一件事.这是否意味着带引号或不带引号是等效的,并且决定使用引号就像将大写字母用作类名,或将接口名以I等开头.

I tried compiling both MyModule and "MyModule" and they compile to the same thing. Does this mean that with or without quotes are equivalent, and deciding to use them is just like using capital letters for class names, or starting interface names with I etc.?

推荐答案

打字稿文档,两种样式之间存在差异. module x {等同于namespace x {,而module "x" {与其他两个都不相同.这绝对令人困惑,这就是为什么文档在所有情况下都使用后一种语法的原因.

As outlined in the Typescript docs, there is a difference between the two styles. module x { is equivalent to namespace x {, while module "x" { is unlike either of the other two. This is definitely confusing, which is why the documentation using the latter syntax in all cases.

然后必须问一个问题,名称空间和所谓的外部模块(即用引号声明的模块)之间有什么区别?

The question then must be asked, what is the difference between a namepsace and a so-called external module (i.e., a module that is declared with quotes)?

我们从文档中获得了一些见识:

We get some insight from the docs:

就像命名空间一样,模块可以包含代码和声明.主要区别在于模块声明了它们的依赖关系.

Just like namespaces, modules can contain both code and declarations. The main difference is that modules declare their dependencies.

模块还依赖于模块加载器(例如CommonJs/Require.js).

Modules also have a dependency on a module loader (such as CommonJs/Require.js).

基本上,使用引号表示它确实是传统Javascript意义上的模块,需要使用显式导入.如果没有引号,则只需创建一个全局对象,而无需任何明确的require即可对其进行引用和利用.

Essentially, using the quotes indicates that it is indeed a module in the traditional Javascript sense that requires explicit import to be used. Without the quotes, you just create a global object that can be referenced and utilized without any explicit requires.

这篇关于为什么某些Typescript模块名称以字符串形式给出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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