Issue with using third-party package types in Angular library creation

My project involves creating a custom voice recognition library, and I have decided to utilize 3rd party package types called @types/dom-speech-recognition. However, upon attempting to integrate these types into my service, the compiler raised errors indicating that it was unable to locate these external types:

Error: ../angular-voice-recognition/src/lib/voice-recognition.service.ts:9:23 - error TS2304: Cannot find name 'SpeechRecognition'.

9   private speechAPI!: SpeechRecognition;
                        ~~~~~~~~~~~~~~~~~


Error: ../angular-voice-recognition/src/lib/voice-recognition.service.ts:40:28 - error TS2304: Cannot find name 'webkitSpeechRecognition'.

40       this.speechAPI = new webkitSpeechRecognition();
                              ~~~~~~~~~~~~~~~~~~~~~~~

To address this issue, I installed the necessary types using

npm install @types/dom-speech-recognition --save

tsconfig.lib.json:

{
  "extends": "../../tsconfig.json",
  "compilerOptions": {
    "outDir": "../../out-tsc/lib",
    "declaration": true,
    "declarationMap": true,
    "inlineSources": true,
    "types": [
      "dom-speech-recognition"
    ]
  },
  "exclude": [
    "src/test.ts",
    "**/*.spec.ts"
  ]
}

voice-recognition.service.ts:

import { Injectable } from '@angular/core';
import {VoiceParams} from "./model/voice-params.model";
import {Observable} from "rxjs";
import {VoiceResult} from "./model/voice-result";
import {VoiceEvent} from "./model/voice-event";

@Injectable()
export class VoiceRecognitionService {
  private speechAPI!: SpeechRecognition;

  ...

  private initialize(params: VoiceParams) {
    if ('webkitSpeechRecognition' in window) {
       ...
    }
  }
}

These are the key areas where modifications were made following the installation of @types/dom-speech-recognition in my library. Could there be a need to export or import the type elsewhere as well?

Answer №1

The error message that is currently being displayed suggests that the definitions for SpeechRecognition and webkitSpeechRecognition are not accessible, despite being installed.

To resolve this issue, consider modifying tsconfig.ts:

{"compilerOptions": {"types": []}}

This adjustment will allow TypeScript to locate and include the necessary types from the installed packages.

Additionally, remember to include the appropriate import statement in voice-recognition.service.ts

import { SpeechRecognition } from 'dom-speech-recognition';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Performing Jasmine unit testing on a component that relies on data from a service, which itself retrieves data from another service within an Angular 2+ application

Attempting to implement unit testing for a service using httpmock has been challenging. The service in question utilizes a method to make http get calls, but I have encountered difficulties in writing the test cases. saveservice.service.ts -- file const ...

List of NPM Configurations: Configurations for the environment - REGISTRY

My C:\Users\XXXXXX.npmrc file contains the following settings: https-proxy=http://proxy.server.com:0000 http-proxy=http://proxy.server.com:0000 strict-ssl=false The proxy is verified, but I encounter an error when installing a Node Package Mana ...

Validate if the translation file exists in ngx-translate

Is there a way to determine if a translation file exists for the language obtained from navigator.language using ngx-translate? I am looking to implement something similar to: if( isLanguageAvailable(navigator.language)) { this.translate.use(navigator.l ...

Can someone explain to me why npm publish keeps saying the package isn't found?

My attempt to upload an npm package to a GitLab registry for the first time has hit a snag. Despite configuring the scope and npm entries as per the provided documentation, I encounter an error when running the command npm publish: npm notice Publishing to ...

Transferring data seamlessly from EF .NET Core 6 to Angular

I am facing an issue while trying to fetch data from my ASP.NET Core 6 backend to Angular: Error: NG0900: Error trying to diff '[object Object]'. Only arrays and iterables are allowed export class EmployeesListComponent { em ...

The Typescript error occurs when trying to assign a 'string' type to a 'SetStateAction<null>'

For my project, I am delving into creating a global context using TypeScript. As a newcomer to TypeScript, I found a helpful guide in this blog post (). Despite following the outlined steps, I keep encountering an error message saying "Type 'string&ap ...

Strategies for effectively mocking an Angular service: During Karma Jasmine testing, ensure that the spy on service.getShipPhotos is expected to be called once. In the test, it should

Currently, I am working on testing a function called getSingleShip in Angular 12 using Karma-Jasmine 4. The aim is to verify if this function is being called by another function named retrieveShip. However, the test results indicate that getSingleShip has ...

Working with Angular: Managing an Array of Objects

After retrieving an array of objects using the code snippet below: this.serviceOne.getRemoteData().subscribe( data => this.MyArray.push(data) ); I encounter issues when trying to iterate through the array using the code snippet bel ...

What is the best way to extract values from case-sensitive query param variables?

I am dealing with a URL that contains the query string id. However, the variable id can appear as either 'id' or 'Id' in the URL. From my understanding, these two variations will be treated differently. To handle URLs like the followin ...

What is the best way to retrieve an Observable in Angular 7?

I recently updated a project from Angular 5.x to 7, and I'm facing an issue with returning an httpClient observable. In Angular 7, there seems to be a change in how the "catch" method works and it's causing an error in my callApi function. The er ...

Issue with the height not being updated in a parent React nested Accordion

Currently, I am in the process of developing the mobile version of my homepage. However, there seems to be a bug in my nested accordion labeled "Projects." The bug is causing an issue where the bottom projects section does not display at the correct height ...

I'm interested in developing a feature that monitors a specific attribute and triggers a function once that attribute hits the value of 100

I am working on a function that will refresh the view once the percentage changes reaches 100: The value is stored in this variable: this.uploadPercent = task.percentageChanges(); This is the function I plan to implement : refreshView(){ Once this.uplo ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

Displaying server errors in an Angular componentIn this tutorial, we

As I work on creating a registration page, my focus has been on posting data to the server. I have successfully implemented client-side and server-side validation mechanisms. Managing client-side errors is straightforward using code such as *ngIf="(emailAd ...

The redirection code is not being executed when calling .pipe() before .subscribe()

My AuthService has the following methods: signUp = (data: SignUp): Observable<AuthResponseData> => { const endpoint = `${env.authBaseUrl}:signUp?key=${env.firebaseKey}`; return this._signInOrSignUp(endpoint, data); }; signIn = (data: SignIn): ...

Can npm packages be integrated into Chrome extensions?

With the abundance of JS modules available on npm these days, I am curious if there is a method to directly incorporate them into creating a Chrome extension. ...

Having trouble sorting out the array in my Node.js code

In a Node.js code snippet, the task is to extract all the links from a web page and then store them in a variable within the function's scope without displaying the data outside of the function. var ineed = require('ineed'); var url = requi ...

Issue with displaying error message and disabling button as Keyup event fails to trigger

Is there a way to assess the user's input in real-time on an on-screen form to ensure that the pageName they enter is not already in the navbarMenuOptions array? If it is, I want to switch the visibility of displayName and displaySaveButton. However, ...

Numerous toggle classes available

Having the following HTML inside a <span> element: <span (click)="openLeft()"></span> A method in a @Component sets a boolean variable like so: private isOpen: boolean; openLeft() { this.isOpen = !this.isOpen; } To toggle classes ...

Tips for customizing labels for boolean filters in DevExtreme data grid

We are looking to change the filter options in the status field (last row) from true/false to Active/Inactive. While there is a coding method to achieve this, we are struggling as we are using a table template. It seems like it should be a simple task but ...