Just starting out with Angular and struggling to understand how to fix the TS(2322) error

Main Code:

export class TodosComponent implements OnInit{
  todos!: Todo[]; 
  localItem: string;
  constructor(){
    const data = localStorage.getItem("todos");
    this.localItem = data;
    if(this.localItem == null){
      this.todos = [];
    }
    else{
      console.log(this.todos);
      this.todos = JSON.parse(data);
    }
  }

Here is the result of my compilation: ERROR src/app/MyComponents/todos/todos.component.ts:14:5 - error TS2322: Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.

14 this.localItem = `custom text` item;

I attempted to resolve it by adding, const localItem: string | null = getValueFromSomewhere(); but unfortunately, it did not work as expected

Answer №1

When retrieving items from the localStorage, there is a possibility of receiving null if the specified key does not exist in the storage. This means that the result of

localStorage.getItem("todos")
could be either a string or null. In this situation, you are assigning it to this.localItem, which will always be treated as a string based on your implementation. To handle this scenario effectively, you can either change the type of this.localItem to string | null, or perform a proper null check on the item before proceeding further. Here's an example of how you can achieve this:

export class TodosComponent implements OnInit{
  todos!: Todo[]; 
  localItem: string;
  constructor(){
    const item = localStorage.getItem("todos");
    if(item == null){
      this.todos = [];
    }
    else{
    this.localItem = item;
      console.log(this.todos);
      this.todos = JSON.parse("localItem");
    }
  }
}

Answer №2

Referencing Wortmann's response.

There are various approaches to address your scenario.

Here are a couple of them :

  1. Modifying the type of localItem to string|null.

export class TodosComponent implements OnInit{
  todos!: Todo[]; 
  localItem: string|null;
  constructor(){
    this.localItem = localStorage.getItem("todos");
    if(this.localItem == null){
      this.todos = [];
    }
    else{
        console.log(this.todos);
        this.todos = JSON.parse("localItem");
    }
}
}

  1. Utilizing the ?? operator.

export class TodosComponent implements OnInit{
  todos!: Todo[];
  localItem: string;
  constructor(){
     this.localItem = localStorage.getItem("todos") ?? "";
    if(this.localItem == ""){
       this.todos = [];
    }
    else{
       console.log(this.todos);
       this.todos = JSON.parse("localItem");
    }
}
}

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

Stripe detects that no signatures match the expected payload

Currently working on setting up a checkout session using Stripe that triggers my webhook upon successful completion. The issue I am facing is an error message stating "error: No signatures found matching the expected signature for payload. Are you passing ...

How can you develop a component that is reusable and make sure that the template reference variable can be assigned to the cdkDropList directive?

https://codesandbox.io/s/hn-kanban-34mvt?file=/src/app/dragDrop/dragDrop.component.html:0-1308 Is it possible to develop a reusable component that allows assigning the #newsList template reference variable to the cdkDropList directive, enabling other comp ...

Having issues with your Typescript in Sublime Text?

The issue with the TypeScript plugin in Sublime Text (version 3126) suddenly arose without any identifiable cause. It seems that the plugin no longer recognizes types, resulting in disabled error highlights and autocompletions. This problem occurred on M ...

How to access a deeply nested object in Angular 2

I am currently grappling with the challenge of extracting information from an object in a JSON response. The structure of the data is shown below: {"bpi":{"2017-10-03":4320.09,"2017-10-04":4225.9238,"2017-10-05":4322.755,"2017-10-06":4370.245,"2017-10-0 ...

Steps for running an Angular application in IntelliJ:1. Open IntelliJ IDEA

I'm currently navigating through IntelliJ to set up Angular support. https://www.jetbrains.com/help/idea/2017.1/using-angular.html#install_angular_cli After successfully creating the project, I am unsure of how to run it. My guess is that I need to ...

Unveiling the types of an object's keys in Typescript

I am currently utilizing an object to store a variety of potential colors, as seen below. const cardColors = { primaryGradientColor: "", secondaryGradientColor: "", titleTextColor: "", borderColor: "&quo ...

Azure DevOps pipeline encounters npm authentication failure

After following the official tutorial on deploying an Angular app to ADO pipelines, I encountered a problem with my yaml file: # Node.js with Angular # Build a Node.js project that uses Angular. # Add steps that analyze code, save build artifacts, deploy, ...

Unable to set textAlign column property in Inovua React Data Grid using typescript

I am currently facing an issue with centering the content of each grid cell in Inovua RDG. A frustrating TypeScript error keeps popping up: Type '{ name: string; header: string; textAlign: string; defaultFlex: number; defaultVisible?: undefined; }&apo ...

Arranging Angular Cards alphabetically by First Name and Last Name

I am working with a set of 6 cards that contain basic user information such as first name, last name, and email. On the Users Details Page, I need to implement a dropdown menu with two sorting options: one for sorting by first name and another for sorting ...

Updating REST API URL on build in Angular CLI

I'm looking to strip out the local server prefix from my REST API URLs (for example, http://localhost:8080) while compiling for production (ng build --prod). I understand that this involves modifying the environment file environment.prod.ts, but I&ap ...

Zod Entry using standard encryption key

I'm attempting to define an object type in zod that looks like this: { default: string, [string]: string, } I've experimented with combining z.object and z.record using z.union, but the validation results are not as expected. const Local ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

Tips for boosting ViteJs development mode performance

One issue I am facing is the slow server performance during development mode. After starting the server and opening the page in my browser, I have to wait 3–6 minutes for it to load! Initially, ViteJs downloads a small amount of resources, but then the ...

Exploring Angular: The Dynamic Declaration of object.property in ngModel

<input [(ngModel)]="Emp."+"dt.Rows[0]["columnname"]"> This scenario results in an undefined value In my current project, I am leveraging the power of a MVC CustomHtmlHelper to generate textboxes dynamically based on database schema. The textbox ...

Differences between Angular 2's ng build and Webpack buildIn this

What is the most effective way to build and deploy my Angular 2 web application? I also need to ensure it can be served as a web bundle resource for my Dropwizard application. Should I stick with ng build to generate my dist folder, or should I custom ...

How can you check the status of a user in a Guild using Discord JS?

Is there a way to retrieve the online status of any user in a guild where the bot is present? Although I can currently access the online status of the message author, I would like to be able to retrieve the online status of any user by using the following ...

Node.js is raising an error because it cannot locate the specified module, even though the path

Currently in the process of developing my own npm package, I decided to create a separate project for testing purposes. This package is being built in typescript and consists of a main file along with several additional module files. In the main file, I ha ...

How to add a class to an element using an Angular 2+ directive

I am working with an Angular 6.0.0 application and I have the requirement to dynamically add classes to HTML elements. My current implementation is functional, but I want to enhance it by making the prefix reusable through a directive. <div class="clas ...

Angular (2/4) application utilizing custom-named routing within a single page architecture

I'm currently working on an Angular application that consists of a login component and a home component which serves as the main handler for the entire single page application. Additionally, I have three more components named users, each with function ...

TSLint warning: Duplicate identifier detected - 'err'

Currently facing an issue with tslint displaying the following error Shadowed name: 'err' Providing the code snippet for reference fs.readdir(fileUrl, (err, files) => { fs.readFile(path.join(fileUrl, files[0]), function (err, data) ...