I have a state that is expecting a string variable. It's a search term. I'm getting this from the search url. But even when I'm checking to see if it's a string I still get an error saying that a variable of type string cannot be string | null
let searched = useLocation().search;
const query = new URLSearchParams(searched);
const [searchedTerm, setSearchedTerm] = useState<string>(typeof query.get('term') === 'string' ? query.get('term') : '');
I specificaly check if it's a string and then add it. The error that I get is this:
Argument of type 'string | null' is not assignable to parameter of type 'string | (() => string)'.
Type 'null' is not assignable to type 'string | (() => string)'.
My guess is that typescript is preventing this, since it does not know if the function will return a string
type again if it has done that in the first go.
Look at this example:
const random = () => {
let x = 3;
let arr = [2,'str'];
return arr[x%2];
};
const letX :string = typeof random() === 'string' ? random() : 'x';
The above will still throw the same error because the return type of the function might not be the same (since it technically can return a number
, although we know it cannot).
So one simple solution would be to create an extra variable:
const random = () => {
let x = 3;
let arr = [2,'str'];
return arr[x%2];
};
const val = random();
const letY :string = typeof val === 'string' ? val : 'y';
const letX :string = typeof random() === 'string' ? random() : 'x';