Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'

I have a dotnetcore 20 and angular4 project that I am trying to create a userService and get the user to my home component. The backend works just fine but the service doesn't. The problem is on localStorage. The error message that I have is :

Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.

And my userService

import { User } from './../models/users'; import { AppConfig } from './../../app.config'; import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http';    @Injectable() export class UserService { constructor(private http: Http, private config: AppConfig) { }  getAll() {     return this.http.get(this.config.apiUrl + '/users', this.jwt()).map((response: Response) => response.json()); }  getById(_id: string) {     return this.http.get(this.config.apiUrl + '/users/' + _id, this.jwt()).map((response: Response) => response.json()); }  create(user: User) {     return this.http.post(this.config.apiUrl + '/users/register', user, this.jwt()); }  update(user: User) {     return this.http.put(this.config.apiUrl + '/users/' + user.id, user, this.jwt()); }  delete(_id: string) {     return this.http.delete(this.config.apiUrl + '/users/' + _id, this.jwt()); }  // private helper methods  private jwt() {     // create authorization header with jwt token     let currentUser = JSON.parse(localStorage.getItem('currentUser'));     if (currentUser && currentUser.token) {         let headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.token });         return new RequestOptions({ headers: headers });     } } 

And my home.component.ts is

import { UserService } from './../services/user.service'; import { User } from './../models/users'; import { Component, OnInit } from '@angular/core';  @Component({ moduleId: module.id, templateUrl: 'home.component.html' })  export class HomeComponent implements OnInit { currentUser: User; users: User[] = [];  constructor(private userService: UserService) {    this.currentUser = JSON.parse(localStorage.getItem('currentUser')); }  ngOnInit() {    this.loadAllUsers(); }  deleteUser(_id: string) {    this.userService.delete(_id).subscribe(() => { this.loadAllUsers() }); }  private loadAllUsers() {    this.userService.getAll().subscribe(users => { this.users = users; }); } 

The error is on JSON.parse(localStorage.getItem('currentUser'));

like image 487
GoGo Avatar asked Oct 24 '17 15:10

GoGo


People also ask

How do I fix type null is not assignable to type string?

The "Type 'string | null' is not assignable to type string" error occurs when a possibly null value is assigned to something that expects a string . To solve the error, use a non-null assertion or a type guard to verify the value is a string before the assignment.

Is not assignable to type key null undefined?

The "Type 'undefined' is not assignable to type" error occurs when a possibly undefined value is assigned to something that expects a different type. To solve the error, use the non-null assertion operator or a type guard to verify the value is of the specific type before the assignment.

Is not assignable to type null react?

To fix 'Type 'null' is not assignable to type 'HTMLInputElement” error in React and TypeScript, we can create a type guard function. Then we use that to check if the ref is an HTMLInputElement . to create the isInputElement type guard. Then we check if elem is falsy and return false if it is.

Is not assignable to parameter of type object?

The error "Argument of type 'X' is not assignable ot parameter of type 'Y'" occurs when the passed in argument and the expected parameter types are incompatible. To solve the error, use a type assertion or a type guard to verify the argument is of a compatible type. Here is an example of how the error occurs.


1 Answers

As the error says, localStorage.getItem() can return either a string or null. JSON.parse() requires a string, so you should test the result of localStorage.getItem() before you try to use it.

For example:

this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}'); 

or perhaps:

const userJson = localStorage.getItem('currentUser'); this.currentUser = userJson !== null ? JSON.parse(userJson) : new User(); 

See also the answer from Willem De Nys. If you are confident that the localStorage.getItem() call can never return null you can use the non-null assertion operator to tell typescript that you know what you are doing:

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!); 
like image 90
Duncan Avatar answered Sep 29 '22 17:09

Duncan