我最近从一个TypeScript文件中引用了几个全局变量,TypeScript标记了以下错误:
Property 'msSpeechRecognition' does not exist on type 'Window & typeof globalThis'.
所以我创建了以下代码添加到我的env.d.ts
(由create-vue
在tsconfig.json
中生成和引用):
declare const msSpeechRecognition: undefined | SpeechRecognitionStatic;
这并没有解决问题。但是,当我将代码转换为以下代码时:
declare var msSpeechRecognition: undefined | SpeechRecognitionStatic;
参考msSpeechRecognition
的错误消失。我理解JavaScript中const
和var
之间的差异,但是在类型声明中使用它们时有什么差异?
当用string
替换SpeechRecognitionStatic
时,我无法重现同样的问题,所以我知道这与SpeechRecognitionStatic
类型有关。这是它的样子(来自@types/webspeechapi
):
interface SpeechRecognitionStatic {
prototype: SpeechRecognition;
new (): SpeechRecognition;
}
错误指示msSpeechRecognition
作为window.msSpeechRecognition
从window
对象访问。您只能通过使用var
声明向globalThis
添加某些内容。如果您想使用const
,则需要将对window.msSpeechRecognition
的引用替换为msSpeechRecognition
。