1

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;
}
Saiansh Singh
  • 583
  • 5
  • 16
  • 3
    Does https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html#global-variables not cover it? – Mike 'Pomax' Kamermans Jul 18 '22 at 01:29
  • @Mike'Pomax'Kamermans, that suggests that `declare var` and `declare const` work the same except for the value being immutable in the `const` case. That's not the case here since using `var` worked for them. – Ryan Pattillo Jul 18 '22 at 01:32
  • 2
    note that it also changes the _scope_ of the declared variable. `var` drastically changes where things live. – Mike 'Pomax' Kamermans Jul 18 '22 at 01:35
  • How exactly are you using `env.d.ts`? Is it a [module](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) or a [script](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-d-ts.html)? – Bergi Jul 18 '22 at 01:46
  • @Bergi I am not sure, I know it was whatever create-vue generates by default. I don’t have any imports in it, but it was a TypeScript declaration file. – Saiansh Singh Jul 18 '22 at 13:47

1 Answers1

1

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.

Ryan Pattillo
  • 331
  • 1
  • 8