Harika
Harika

Reputation: 355

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.

Upvotes: 16

Views: 59051

Answers (3)

Kris Stern
Kris Stern

Reputation: 1350

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 ?? ''}/>

Upvotes: 2

Experimenter
Experimenter

Reputation: 2477

You can remove optional modifier in two ways.

1-st by Required utility type:

interface Foo{
  a?: string;
  b?: number;
}

type Foo2 = Required<Foo>

2-nd by Mapping Modifiers:

// Removes 'optional' attributes from a type's properties
type Bar = {
  [P in keyof Foo]-?: number;
}

Also you might want to constructs a type by excluding null and undefined from Type by NonNullable utility type:

type NonNullable<T> = Exclude<T, null | undefined>;

Upvotes: 1

HereBeAndre
HereBeAndre

Reputation: 308

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.

Upvotes: 20

Related Questions