Use Typescript to access and utilize the value stored in local storage by using the

Trying to retrieve the language setting from localHost and implement it in a translation pipe as shown below:

transform(value: string): string {...
localStorage.setItem("language", JSON.stringify("en"));
let language = JSON.parse(localStorage.getItem("language") ?? "en");
language = language as keyof typeof translates[number];
const translates: {
      key: string;
      cz: string;
      en: string;
    }[]
let returnTranslate = "";

    translates.forEach((item) => {
      if (item["key"] === value) {
        returnTranslate = item[language];
      }
    });

Encountering an error message stating:

'Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ key: string; cz: string; en: string; }''

This problem occurs in the following part of the code:

item[language]

Answer №1

The TypeScript compiler is throwing errors because you are attempting to use a type that is inferred as any.

But why is your language variable being treated as any? This happens because of the initial assignment.

let language = JSON.parse(localStorage.getItem("language") ?? "en");
// Here, 'language' is considered as type any

In this block of code, using as helps in explicitly defining the type:

language = language as keyof typeof translates[number];

While using as temporarily informs the compiler about the forced type, using the language variable (which is still of type any) as an index later in the code results in compilation errors.

Instead, you should specify the type explicitly where you intend to use the language as the index:

returnTranslate = item[language as keyof typeof translates[number]];

To simplify this process and ensure that your language variable is always of type keyof typeof translates[number], you can adjust it at the start:

let language = JSON.parse(localStorage.getItem("language") ?? "en") as keyof typeof translates[number];

This modification eliminates the need for the line

language = language as keyof typeof translates[number];
.

Try running this example on the TypeScript playground

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

Troubleshooting compilation problems in Angular2 with nested components

I have created two components in Angular2 using TypeScript: app/app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', styles : [` .parent { background : #c7c7c7; ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

Whenever I choose an ionic tab that has a changing URL, the tab does not appear as highlighted

My issue involves the ion tab setup in tabs.page.html. The user_id is set in the tabs.page.ts file within the same directory, ruling out any issues there. <ion-tabs> <ion-tab-bar slot="bottom"> ... <ion-tab-button tab=“profil ...

Handling errors in Angular and rxjs when encountering undefined returns in find operations

I am currently faced with the challenge of catching an error when the variable selectionId, derived from my route, is null or contains an invalid value. My code structure has a mechanism in place to handle errors when the category variable is undefined, bu ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

Encountering an issue with Angular2 while attempting to map data from a WebAPI (Error: Unable to perform data differentiation

I've been struggling to retrieve data from an API and display it in a list using ngFor. I've experimented with promises, observables, map, subscribe, async pipe, but haven't had any success. It seems like the API is being called, but I keep ...

Using conditional styles with Angular 2

I am currently working on applying conditional styles to a table. For instance, if a user's "obsolete" property is true, I want to display their information with a <del> tag. I have searched online for solutions, and while I am aware of using *n ...

Is it possible for a React selector to retrieve a particular data type?

As a newcomer to React and Typescript, I am currently exploring whether a selector can be configured to return a custom type. Below is a basic selector that returns a user of type Map<string, any>: selectors/user.ts import { createSelector } from ...

Support for Chrome in Angular 8

Can someone please advise on the minimum version of Google Chrome that is supported by Angular 8? Additionally, I am looking for a way to prompt users to update their Chrome browser if it doesn't meet the required version. My Angular application seems ...

Encountered an error while attempting to run npm install for angular2-tree-component

I recently attempted to install the angular2-tree-component, but encountered a failure in the process. As I am still gaining experience with this technology stack, I would greatly appreciate some assistance in resolving this issue... /R/VKS/oryol/oryo ...

Storing information upon refresh in Angular 8

When it comes to inter-component communication in my Angular project, I am utilizing BehaviourSubject from RXJS. Currently, I have a setup with 3 components: Inquiry Form Where users enter an ID number to check for summon-related information. This data ...

Tips for utilizing generics to determine the data type of a property by its name

I am seeking a method to determine the type of any property within a class or a type. For instance, if I had the classes PersonClass and PersonType, and I wanted to retrieve the type of the nationalId property, I could achieve this using the following cod ...

Angular two - Communication between parent and children components using a shared service

I am currently working on establishing communication between child components, but according to the documentation, I need to utilize services for this purpose. However, I am facing challenges in accessing service information. When I try to assign the retur ...

Issue encountered when attempting to convert Angular application to Angular Universal

While attempting to convert my Angular App into Angular Universal, I encountered an issue. I used the command "ng add @nguniversal/express-engine --clientProject my-app" An error occurred: Module not found - '@schematics/angular/utility/json-file&apo ...

Is it possible to execute TypeScript class methods in asynchronous mode without causing the main thread to be blocked?

Creating an app that retrieves attachments from specific messages in my Outlook mail and stores the data in MongoDB. The challenge lies in the time-consuming process of receiving these attachments. To address this, I aim to execute the task in a separate t ...

Exporting Arrays in Ionic Angular with Typescript is an essential feature

When trying to access an exported component in Typescript, there may be issues with importing the module correctly into another component. An error message is displayed when calling the AddToArray method: Cannot read property 'push' of undefi ...

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

The character 'T' cannot be assigned to the data type 'number'

When working with an optional type argument function RECT(T), I encountered a situation where I need to check if the argument is an instance of date. If it is, I convert it to a number; if not, I use the number directly. However, I keep getting an error ...

The parameter "path" must be a string type. Instead, we received type undefined. This issue is specific to Ionic 4 on Windows

Encountered an unexpected error that is hindering development on a Windows PC, even though building the app works fine on a Mac. The error message received is: cordova build android --stacktrace config file undefined requested for changes not found at ...