本文介绍了什么是“环境类型"?在 Typescript 打字工具中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说环境"一词用于描述使用 typings 工具下载的类型定义.不过,这意味着什么?

I hear the term "ambient" used to describe type definitions downloaded with the typings tool. What does that mean, though?

我似乎找不到它的直接定义或 --ambient 标志.

I can't seem to find a straightforward definition of it or the --ambient flag.

推荐答案

来自 TypeScript 文档:

From the TypeScript docs:

环境声明将变量引入 TypeScript 范围,但对发出的 JavaScript 程序的影响为零.程序员可以使用环境声明来告诉 TypeScript 编译器某个其他组件将提供一个变量.例如,默认情况下,TypeScript 编译器将打印使用未定义变量的错误.要添加浏览器定义的一些公共变量,TypeScript 程序员可以使用环境声明.

https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#1.1

再简单一点.环境声明告诉 TypeScript 编译器,当 JavaScript 执行时,会存在一些 TypeScript 编译器现在看不到的东西(因为它不是 TypeScript).

To put it a little more simply. Ambient declarations tell the TypeScript compiler that when the JavaScript is executed, something will exist that the TypeScript compiler can't see right now (Because it isn't TypeScript).

想象一下,如果您正在编写使用 jQuery 的代码.如果您只是尝试编写 $(),TypeScript 会认为您使用的是未声明的变量 $ 并且会抛出错误.像 declare var $ 这样的环境声明告诉 TS 编译器,即使 $ 对编译器不可见,但在 JS 执行时它会存在.

Imagine if you are writing code that uses jQuery. If you just try to write $() TypeScript will think you are using an undeclared variable $ and will throw an error. Ambient declarations like declare var $ tell the TS compiler that, even though $ isn't visible to the compiler, it will exist when the JS is executed.

这篇关于什么是“环境类型"?在 Typescript 打字工具中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 03:24