` Error is : Type 'string | null | undefined' is not assignable to type '" /> ` Error is : Type 'string | null | undefined' is not assignable to type '" /> ` Error is : Type 'string | null | undefined' is not assignable to type '"/>

How can i define type of src in tsx in nextjs

82 Views Asked by At
<Image src= { sessionData?.user.image} alt="user"   width={100}
                height={100}  />`

Error is :

Type 'string | null | undefined' is not assignable to type 'string | StaticImport'.
Type 'undefined' is not assignable to type 'string | StaticImport'.ts(2322)
image-component.d.ts(7, 5): The expected type comes from property 'src' which 
is declared here on type 'IntrinsicAttributes & Omit<DetailedHTMLProps<ImgHTMLAttributes<HTMLImageElement>,
HTMLImageElement>, "ref" | ... 5 more ... | "srcSet"> & { ...; } & RefAttributes<...>'

Is There any way to give it a type or should i leave as it is becuase its not giving me any error in web page

1

There are 1 best solutions below

0
Quentin On

sessionData?.user.image could be undefined (because you are using optional chaining.

Assigning undefined to src simply doesn't make sense.

So you need to test for that state and do something different.

What the different thing is, isn't a programming problem problem. Maybe you want to show a different image. Maybe you want to not show an image at all. Maybe something else. Maybe that's a condition that should be impossible to reach in your app (but TypeScript doesn't know that) and you want to throw a fatal exception or display an error message.

How you fix it depends on what you want to do under those circumstances. It will likely involve either taking a step back and adding an if or following the sessionData?.user.image expression with a nullish coalescing operator and providing an alternative value. This is a design decision you need to make (or pass to some other responsible person).