简体   繁体   English

在打字稿定义中声明 var 和声明 const 有什么区别?

[英]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-vuetsconfig.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 中constvar之间的区别,但是在类型声明中使用它们时有什么区别?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM