简体   繁体   中英

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:

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 ):

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. I understand the differences between const and var in JavaScript, but what are the differences when using them in type declarations?

I couldn't reproduce this same issue when replacing SpeechRecognitionStatic with string , so I know it's something related to the SpeechRecognitionStatic type. Here is how it looked like (brought from @types/webspeechapi ):

interface SpeechRecognitionStatic {
    prototype: SpeechRecognition;
    new (): SpeechRecognition;
}

The error indicates that msSpeechRecognition is being accessed from the window object as window.msSpeechRecognition . You can only add something to globalThis by declaring it with var . If you want to use const instead, you will need to replace references to window.msSpeechRecognition with just msSpeechRecognition .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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