I have code like below:
type ItemProps = {
status?: string;
}
<Items status={status!} /> // error here: warning Forbidden non-null assertion
// @typescript-eslint/no-non-null-
assertion
I am getting a forbidden non-null assertion error.
How can I fix this error?
I have tried
<Items status={status && status}/>
but this doesn't seem correct.
Why do you want to use the "non-null assertion operator"?
The status property can either be string | undefined.
What about passing an empty string or perhaps assigning a default value when you don't want to specify a value for status?
<Items status={status || ''}/>
Or:
type ItemProps = {
status?: string;
};
const Items: React.FC<ItemProps> = ({ status = 'statusDefaultValue' }) => <div>Some JSX</div>
It's a bit hard for me to understand your case without knowing the context. Hope this can help.
You can try to use the nullish coalescing operator (??) instead of a logical or (||), as it is a safer operator as some might prefer, like the following:
<Items status={status ?? ''}/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With