什么是环境声明 [英] What are ambient declarations

查看:27
本文介绍了什么是环境声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到很多使用提及环境声明的文章.例如这篇文章.这些是什么?有人可以提供一个例子吗?环境声明是在现有打字稿文件之外创建但在这些文件中使用的类型的声明吗?所有声明都环境吗?

I've been seeing a lot using articles mentioning ambient declarations. For example this article. What are they? Can somebody provide an example? Is an ambient declaration a declaration of a type created outside existing typescript files but used in these files? Are all declarations ambient?

据我所知,ambient declarations 不会产生任何 javascript 代码,而是使用 declare 关键字定义的.这是环境声明的唯一情况还是还有其他情况?

As I understand ambient declarations don't produce any javascript code and are defined using declare keyword. Is this the only case of ambient declarations or there are others?

推荐答案

是的,环境声明让你告诉编译器关于现有变量/函数/等.

Yes, ambient declarations let you tell the compiler about existing variable/functions/etc.

例如,假设您在网页中使用一个添加全局变量的库,假设它的名称是 ON_READY 并且它是对函数的引用.
您需要为其分配一个函数,以便执行以下操作:

For example let's say that in your web page you're using a library that adds a global variable, let's say that it's name is ON_READY and it is a reference to a function.
You need to assign a function to it so you'll do something like:

ON_READY = () => {
    console.log("ready!");
    ...
};

编译器会抱怨:

找不到名称ON_READY"

Cannot find name 'ON_READY'

所以你使用环境声明来通知编译器这个变量存在以及它的类型是什么:

So you use an ambient declaration to inform the compiler that this variable exists and what it's type is:

declare var ON_READY: () => void;

现在它不会抱怨找不到它了.

Now it won't complain about not finding it.

当使用 declare 关键字时,它始终是环境关键字,就像您链接到的文章中所说的那样:

When using the declare keyword it is always ambient, just like it says in the article you linked to:

declare 关键字用于环境声明定义一个可能不是源自 TypeScript 文件的变量

The declare keyword is used for ambient declarations where you want to define a variable that may not have originated from a TypeScript file

非环境声明只是普通的变量/函数声明:

Non-ambient declarations are just normal variable/function declarations:

let x: number;
const y = "string";
var a = () => { console.log("here"); }

这篇关于什么是环境声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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