0

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

1 Answer 1

2

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

TS Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.