什么是环境声明

编程入门 行业动态 更新时间:2024-10-27 08:34:49
本文介绍了什么是环境声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 09:44:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1187987.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:声明   环境

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!