Lara
Lara

Reputation: 3021

Type 'string | null' is not assignable to type 'string | undefined error with TypeScript

I have a plain markup code like below

<ListItemText title={details} />

My application is using typescript, and its giving error at title={details} like

Type 'string | null' is not assignable to type 'string | undefined error with TypeScript

How to correct it? What's the right way to handle this?

Upvotes: 1

Views: 1558

Answers (2)

johannchopin
johannchopin

Reputation: 14844

Your issue here is that the title prop need a type string | undefined. So (as CherryDT mentioned) you need to be sure that details will always be from the same type as title.

You just need to declare it:

const details: string | undefined = ...

Then in you case you will probably have another error because you assign null to details. If this is the case just assign undefined instead of null.

Upvotes: 0

KR Tirtho
KR Tirtho

Reputation: 464

You have to simply give an placeholder for the null value... CODE

<ListItemText title={details??""} />

It will only check if the value is nullish instead of checking falsy(null, undefined, NAN, ""), don't mix with || or operator. If details is null, then it will pass the empty string (which is eventually a string type) to the prop..

Upvotes: 1

Related Questions