问题描述
限时送ChatGPT账号..declare
关键字的用途是什么?
What is the purpose of the declare
keyword?
type Callback = (err: Error | String, data: Array<CalledBackData>) => void;
对比
declare type Callback = (err: Error | String, data:Array<CalledBackData>) => void;
找不到解释 TS 中 declare
关键字的用途的文档.
Cannot find docs that explain the purpose of the declare
keyword in TS.
推荐答案
这是一个真实的例子.
我有一个使用 Webpack 热中间件的 TypeScript React 应用程序.Webpack 热中间件不是用 TypeScript 编写的,而是用老式的 JavaScript 编写的.所以它没有 TypeScript 编译器可以检查的类型声明.
I have a TypeScript React app that uses the Webpack Hot Middleware. The Webpack Hot Middleware is not written in TypeScript, but in good old-fashioned JavaScript. So it has no type declarations that the TypeScript compiler can check against.
当我运行我的代码时,来自 Webpack 热中间件的对象 module
存在,我可以对它进行 console.log,尽管它是隐藏在我的新 TypeScript React 应用程序中的老式 JavaScript.
When I run my code, the object module
from the Webpack Hot Middleware exists, and I can console.log it despite it being good old-fashioned JavaScript hiding in my fancy new TypeScript React app.
module
对象也有键,比如module.hot
,键可以有值.但是 TypeScript 设计时编译器(至少在 VSCode 中)在它下面画了一个红色的波浪线,说 property 'hot' does not exist
.但它确实存在!
The module
object also has keys, such as module.hot
, and the keys can have values. But the TypeScript design time compiler (in VSCode at least) draws a red squiggly under it saying property 'hot' does not exist
. But it does exist!
为了让 TypeScript 编译器同意,声明如下:
To make the TypeScript compiler agree, declare it like this:
declare let module: any
现有的 module
对象,现在有一个 any
类型,这让 TypeScript 编译器现在很高兴,红色波浪线消失了,现在我可以继续编译和编写我的其他代码.
The existing module
object, now has a type of any
, which makes the TypeScript compiler happy now, red squiggly gone and now I can continue to compile and write my other code.
如果去掉关键字declare
,只写let module:any
,它不会编译,而是说'module'已经存在
代码>.这就是环境".在接受的答案意味着.
If you remove the keyword declare
, and just write let module: any
, it will not compile, instead saying that 'module' already exists
. That's what "ambient" in the accepted answer means.
这篇关于TypeScript 中声明关键字的用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论