相关文章推荐
乐观的苦瓜  ·  WCF: IIS Log ...·  11 月前    · 
玩滑板的罐头  ·  Invoking the ...·  1 年前    · 
失眠的烤地瓜  ·  IIS FTP Server ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

Ask Question

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'));

Don't you have to end a type with a ? to say that it's nullable? I'm not sure where you're specifying the string type. – Carcigenicate Oct 24, 2017 at 15:56 In this case, I don't even know which one is null and which one is a string. The error is on localStorage. It just doesn't get the user from localStorage. – GoGo Oct 24, 2017 at 16:11

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')!);
                Hi! Thanks for this answer, it makes sense, yet I tried it here but am still running into that same error, mind a look see? :) stackoverflow.com/questions/54715260/…
– Leon Gaban
                Feb 15, 2019 at 18:38
                Actually, sorry the first example you posted works, the 2nd one didn't :) this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
– Leon Gaban
                Feb 15, 2019 at 18:40
                Thanks, I updated my answer to reference yours in case people don't look far enough down the page.
– Duncan
                May 28, 2019 at 16:08
                ONLY If you are confident that the value   can NEVER return null you can use the non-null assertion operator to tell typescript that you know what you are doing
– Michael Freidgeim
                May 16, 2020 at 13:55

The non-null assertion operator worked for me very well:

(1). in my case

this.currentUserSource.next(null!)

(2). in your case

this.currentUser = JSON.parse(localStorage.getItem('currentUser')!);
                private restrictedWord(control: FormControl): {[key: string]: any} {         return control.value.includes('moo') ? {'restrictedWord': 'moo'} : null!     } where I was using null then gave me error
– asifaftab87
                Mar 7, 2022 at 9:09

Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.

export class TodoComponent implements OnInit {
  loacalitems!: string;
  todos!: Todo[];
  constructor() {
    this.loacalitems = localStorage.getItem("todos");

because localStorage.getItem() return string or null solve this problem any variable this type error is define variable

localitems!: string | null;

this variable holds to type values string or null. then write logic

Short hande if else

this.todos = this.localitems !== null ? JSON.parse(this.localitems) : [];

if-else

if(this.localitems !== null){
   // item not null code
   this.todos = JSON.parse(this.localitems)
}else{
   // item is null code
   this.todos = []
  localsetItem: string | null;
  constructor() { 
  this.localsetItem=localStorage.getItem("todos")
  if(this.localsetItem == null)
    this.todos  = [];
    this.todos=JSON.parse(this.localsetItem);

Any ideas for this:

export const useStateWithLocalStorage = (defaultValue: string[], key: string) => {
  const [value, setValue] = useState(() => {
    const storedValues = localStorage.getItem(key);
    return storedValues !== null ? JSON.parse(storedValues) : defaultValue;
  useEffect(() => {
    localStorage.setItem(key, JSON.stringify(value));
  }, [key, value]);
  return [value, setValue];

I have struggled a lot making this issue worked in my case by using the above solution but none of them succeeded. What workied for me is:

   const serializableState: string | any = localStorage.getItem('globalState');
    return serializableState !== null || serializableState === undefined ? JSON.parse(serializableState) : undefined;

I had to cast my variable to string | any and then checked if the variable is null or undefined before parsing it

You should add supporting information to your answers. An explanation of the non nullish assertion used here would be nice! – zenly Apr 28, 2022 at 15:48 ! is a Non-null assertion operator that tell the compiler explicitly that you are sure the type of value is not null or undefined – Anouar BAKRI May 11, 2022 at 13:55

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.