什么意思"环境"在TypeScript中

时间:2014-11-15 13:47:07

标签: typescript

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

  

无法在环境上下文中声明函数实现。

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

我试图用我的母语来理解,但在这种情况下却无法理解。这有点像current context我会说但是没有用。

出现这个消息是因为我试图declare一个无法声明的类,只有module才可以。我已修复它但仍然不理解错误消息的含义。

2 个答案:

答案 0 :(得分:17)

氛围:the character and atmosphere of a place.。存在TypeScript声明文件以告诉编译器它正在运行的环境。因此,环境上下文这个词。您只能在声明上下文中执行声明而不能实现

PS:Ambient declaration covered here

答案 1 :(得分:7)

环境仅表示"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的{​​{1}}” (其他情况类似)。

您还可以将环境视为TS中的declare关键字。像interfacestype aliases这样的所有类型声明在定义上都是隐含的,对于编译器来说很明显,这些声明对运行时没有影响。

string

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

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

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") } } 是一个npm软件包,实现代码应该位于"mymod"下的主.js文件中,而上述类型则位于单独的"node_modules/mymod"文件中。

相关问题