![](/img/trans.png)
[英]What's the difference between "declare class" and "interface" in TypeScript
[英]What is the difference between declare var and declare const in typescript definitions?
我最近从 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;
}
该错误表明正在从window
对象访问msSpeechRecognition
作为window.msSpeechRecognition
。 您只能通过使用var
声明来向globalThis
添加一些内容。 如果您想改用const
,则需要将对window.msSpeechRecognition
的引用替换为msSpeechRecognition
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.