Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix the forbidden non-null assertion in TypeScript and React?

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.

like image 654
Harika Avatar asked Dec 04 '25 22:12

Harika


2 Answers

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.

like image 50
HereBeAndre Avatar answered Dec 06 '25 15:12

HereBeAndre


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 ?? ''}/>
like image 20
Kris Stern Avatar answered Dec 06 '25 13:12

Kris Stern