Angular2: Web Speech API - Voice recognition

Aral Roca picture Aral Roca · Jun 29, 2016 · Viewed 10.3k times · Source

After reading the documentation of webkitSpeechRecognition (voice recognition in Javascript) I tried to implement it in Angular 2.

But when I did this:

const recognition = new webkitSpeechRecognition();

TypeScript say this error:

[ts] Cannot find name 'webkitSpeechRecognition'. any

And if I try to extract webkitSpeechRecognition from window:

if ('webkitSpeechRecognition' in window) {

    console.log("Enters inside the condition"); // => It's printing

    const { webkitSpeechRecognition } = window; // => TypeScript Error
    const recognition = new webkitSpeechRecognition();
}

If I comment the last two lines the console.log is printed, enters to the condition! webkitSpeechRecognition exists inside window!! But if not comment the last two lines the TypeScript error now is this:

[ts] Type 'Window' has no property 'webkitSpeechRecognition' and no string index signature.
const webkitSpeechRecognition: any

How can I create a new recognition in Angular 2? Has anybody tried it?

Answer

Aral Roca picture Aral Roca · Jun 29, 2016

Finally I solved creating an interface!!

export interface IWindow extends Window {
  webkitSpeechRecognition: any;
}

And:

const {webkitSpeechRecognition} : IWindow = <IWindow>window;
const recognition = new webkitSpeechRecognition();