React, typescript - Argument of type 'string | null' is not assignable to parameter of type 'string'

Viewed 31

I have a simple react, typescript form where I'm trying to pass a value to localstorage

I'm getting the error

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

Not sure how to fox this error, can anyone help

1 Answers

You likely have a scenario close in nature to the example below.

let input: string | null = null;
const func = (val: string) => {
  // some function requiring `val` param to be of type `string`  
};

// Check that input is of type string before passing to function
if(typeof input === "string") {
  func(input);
}

Some function requires it's param to be of type string, but the arg being passed in has a type that can be a string OR null. What you need to do is some sort of type check to ensure that the function is only called if it's arguments match the required signature.

In the case of localStorage, a returned value will either be of string if the key exists, or null if the key does not exist.

const KEY = "someKey";
const item = localStorage.getItem(KEY); // item will be of type 'string | null'

if(!item) { 
  // item is null
} else {
 // item is string
}
Related