繁体   English   中英

TypeScript 中的“环境”是什么意思

[英]What means “ambient” in TypeScript

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

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

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

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

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

英文单词

氛围: the character and atmosphere of a place. .

打字稿版本

TypeScript 声明文件的存在是为了告诉编译器它运行的环境。 因此这个词环境上下文 你只能做一个声明上下文的声明,而不是实现

例如,如果您在原始 JS 文件中声明了一些awesomeLibrary ,而 TypeScript 不知道以下内容将会出错:

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

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

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

更多的

更多关于环境声明

Ambient 的意思是“没有实现”

环境声明仅存在于类型系统中并在运行时被擦除:

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

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

// ambient variable declaration
declare const myVar: string;

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

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

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文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM