【问题标题】:What means "ambient" in TypeScriptTypeScript 中的“环境”是什么意思
【发布时间】:2015-01-12 19:38:52
【问题描述】:

我不明白下面句子中的 ambient 是什么意思:

函数实现不能在环境上下文中声明。

我不确定这个词的一般含义,(英语不是我的母语),如果这里有特定含义,我也不明白。

我试图用我的母语理解,但在这种情况下无法理解。这有点像 current context 我会说但它不起作用。

该消息出现是因为我试图declare 一个无法声明的类,只有module 可以。我已经修复了,但还是不明白这里的错误信息的含义。

【问题讨论】:

标签: typescript


【解决方案1】:

英文单词

环境:the character and atmosphere of a place.

TypeScript 版本

TypeScript 声明文件的存在是为了告诉编译器它运行的环境。因此这个词环境上下文。您只能在声明上下文中执行 declarations 而不能在 implementations 中执行。

例如如果您在 TypeScript 不知道的原始 JS 文件中声明了一些 awesomeLibrary,则会出现以下错误:

awesomeLibrary = 123; // Error: `awesomeLibrary` is not defined

所以你可以在环境上下文中声明它,现在 TypeScript 就可以了:

declare var awesomeLibrary: any;
awesomeLibrary = 123; // allowed

更多

More on ambient declarations.

【讨论】:

  • 所以简而言之,你不能在 .d.ts 文件中声明除了接口之外的任何东西。
  • 没有。还有其他声明,例如declare var foo:number; 不是接口。但是,当您尝试将 foo 分配给 123 时,您不能执行 declare var foo = 123 ... 这是一个实现。
  • 我明白环境在现实世界中的含义。但是是什么让 TypeScript 中的某些东西成为环境?
  • 在我的情况下,我在 d.ts 中定义接口和类,我的类应该没有实现,但我得到了那个错误,在查看后我意识到我仍然有构造函数每个类的实现。我认为更“开发人员友好的描述”会受到欢迎,例如“定义类不能包含实现,请检查您没有实现任何构造函数或函数”,以及一些解释其工作原理和常见缺陷的链接。跨度>
  • 这甚至不是答案,提供的链接也无济于事。
【解决方案2】:

环境仅仅意味着"without implementation"

环境声明只存在于类型系统中,并在运行时被删除:

// ambient module declaration
declare module "mymod" { /*... */ }

// ambient namespace declaration
declare namespace MyNamespace { /*... */ }

// ambient variable declaration
declare const myVar: string;

例如declare const myVar: string 就像对编译器的承诺:“假设将有一个const myVar 类型在运行时 定义string”(其他情况类似)。

您也可以将环境视为 TS 中的 declare 关键字。所有类型声明,如 interfacestype aliases,都是隐式定义的,因为编译器很清楚,它们对运行时没有影响。

declare type MyType = {a: string} // is valid
type MyType = {a: string} // shorter, so just leave "declare" out

“不能在环境上下文中声明函数实现。”

如前所述,环境声明不能包含运行时代码,例如:

declare module "mymod" {
    function foo() { // error: An implementation cannot be declared in ambient contexts.
        console.log("bar")
    }
}

鉴于"mymod" 是一个npm 包,实现代码宁愿在"node_modules/mymod" 下的主.js 文件中,以上类型驻留在单独的.d.ts 文件中。

【讨论】:

  • 到目前为止,我在这个主题上看到的最全面的答案。我现在真的明白了。谢谢!
猜你喜欢
  • 2016-08-04
  • 1970-01-01
  • 2020-05-30
  • 2019-02-24
  • 2020-06-08
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多