[英]What is the difference between declare var and declare const in typescript definitions?
I recently had a few global variables that I was referencing from a TypeScript file that TypeScript marked with the following error:我最近从 TypeScript 文件中引用了一些全局变量,TypeScript 标记了以下错误:
Property 'msSpeechRecognition' does not exist on type 'Window & typeof globalThis'.
So I created added the following code into my env.d.ts
(generated and referenced in tsconfig.json
by create-vue
):所以我创建了将以下代码添加到我的
env.d.ts
中(由create-vue
在tsconfig.json
中生成和引用):
declare const msSpeechRecognition: undefined | SpeechRecognitionStatic;
This didn't fix the problem.这并没有解决问题。 However, when I switched the code to the following:
但是,当我将代码切换为以下内容时:
declare var msSpeechRecognition: undefined | SpeechRecognitionStatic;
The error on the reference to msSpeechRecognition
disappeared.对
msSpeechRecognition
的引用错误消失了。 I understand the differences between const
and var
in JavaScript, but what are the differences when using them in type declarations?我了解 JavaScript 中
const
和var
之间的区别,但是在类型声明中使用它们时有什么区别?
I couldn't reproduce this same issue when replacing SpeechRecognitionStatic
with string
, so I know it's something related to the SpeechRecognitionStatic
type.用
string
替换SpeechRecognitionStatic
时我无法重现同样的问题,所以我知道这与SpeechRecognitionStatic
类型有关。 Here is how it looked like (brought from @types/webspeechapi
):这是它的样子(来自
@types/webspeechapi
):
interface SpeechRecognitionStatic {
prototype: SpeechRecognition;
new (): SpeechRecognition;
}
The error indicates that msSpeechRecognition
is being accessed from the window
object as window.msSpeechRecognition
.该错误表明正在从
window
对象访问msSpeechRecognition
作为window.msSpeechRecognition
。 You can only add something to globalThis
by declaring it with var
. 您只能通过使用
var
声明来向globalThis
添加一些内容。 If you want to use const
instead, you will need to replace references to window.msSpeechRecognition
with just msSpeechRecognition
.如果您想改用
const
,则需要将对window.msSpeechRecognition
的引用替换为msSpeechRecognition
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.