How to tell React ts component that a nullable state is guaranteed not to be null so that we don't have to confirm over and over?
Situation:
- In a React TS component, there's a nullable state (initial value is set to null)
-
useEffect
inside the component guarantees that the state is not null (because the logic of theuseEffect
redirects users back if the value is null) - Everytime I use
someState
in the component I have to write code to make sure that thesomeState
is not null (e.g. if (someState !== null) doSomething) otherwise TS complains. Is there any possible way to tell(or set) the component that a state is not null for sure so that I don't have to write if state all the time when I use the state?
If you have a special remedy for it, please let me know.
// inside a component
const [someState, setSomeState] = useState<ISomeState | null>(null)
useEffect(() => {
const res = getSomeStateValue();
// let's say the function `getSomeStateValue()` is async
// and **redirect user if the value for `someState` is null**
//so literally when a user is in this component, someState will never be null
},[])
// in some function
const someFunction = () => {
const aState = someState.someKey // this line throws error 'someState can be null` and I have to write like below not to have error everytime I use someState
if (someState !== null) // do something with the `someState` and the null error is now gone
}
If I understand your question correctly, you can use what's known as optional chaining to handle null (objects) gracefully. You can read more about it here.
Since I don't have the full context in which you are using someState
, allow me to contrive an example. Let's say someState
is an object that has a property called someKey
which in turn, has a value.
someState: { someKey: someValue }
If you tried to reference someState.someKey
, you may get a Typescript error because of the fact that someState is initially set to null and therefore, at some point, can be null.
You could solve this via optional chaining, or simply put, by placing a question mark after the object whose potential null (or undefined) value is causing the issue: someState?.someValue
Let me know if this helps clear up your Typescript errors.