![](/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.