1

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?

3
  • 1
    I suppose that in one place you set details = null or you define it as const details: string | null? Commented Aug 24, 2020 at 17:39
  • Ensure that details can't be null, only a string or undefined. Commented Aug 24, 2020 at 17:39
  • @johannchopin Yes, its as you said, what's the correct way? Commented Aug 24, 2020 at 17:43

2 Answers 2

1

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..

Sign up to request clarification or add additional context in comments.

2 Comments

This works but writing code like that make TypeScript worthless.
Yeah, but you have to match the types of both input & output & you havn't mentioned your types. Try avoiding this method in TS. Just match the both of the types or add null type to details prop by doing details?: string | null in your prop type defination, this will do the trick.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.