Below is a small example, where I would like to ask, why the eslinter for typescript is complaining about the object, that it could be possibly undefined in that case, where an undefined-check is actually added, just that it is extracted into a separate function, so that is gets a more meaningful name.
import { ReactElement } from "react";
import "./styles.css";
interface Item {
id?: string;
images?: string[];
}
const itemHasImages = (item: Item): boolean =>
item.images !== undefined && item.images.length > 0;
const renderItem = (item: Item): ReactElement => {
if(itemHasImages(item)){ // <<< using this the compiler complains below in JSX that item could possibly be null
// vs if(item.images !== undefined && item.images.length > 0) <<< here the compiler recognizes the check
return (
<>
<img src={item.images[0]} alt={""} />
</>
);
} else {
return <></>
}
};
export default function App() {
const dummyItems = [
{
images: ["https://picsum.photos/200/300", "https://picsum.photos/200/300"]
},
{
images: ["https://picsum.photos/200/300", "https://picsum.photos/200/300"]
}
];
if (itemHasImages(dummyItems[0])) {
console.log("hello")
renderItem(dummyItems[0]);
} else {
return <div>Hello</div>;
}
return <div>Hello</div>;
}
Please apologize weak formatting, for better interaction you can find a code-sandbox link here:
https://codesandbox.io/s/unruffled-bogdan-c74u6?file=/src/App.tsx