qui*_*987 9 javascript typescript typescript-typings
下面是一个小例子,我想问,为什么 typescript 的 eslinter 抱怨该对象,在这种情况下它可能是未定义的,实际上添加了未定义检查,只是将其提取到单独的函数,因此它得到一个更有意义的名称。
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>;
}
Run Code Online (Sandbox Code Playgroud)
请对弱格式表示歉意,为了更好的交互,您可以在此处找到代码沙盒链接:
https://codesandbox.io/s/unruffled-bogdan-c74u6?file=/src/App.tsx
为什么 typescript 的 eslinter 会抱怨该对象,它可能是未定义的?
原因是因为你添加了一个?(可选)接口声明中的属性。
解决这个问题的一种方法是在使用 ? 渲染它时检查是否未定义。操作员。
<img src={item.images ? item.images[0] : ""} alt={""} />
Run Code Online (Sandbox Code Playgroud)
请注意,这只是隐藏问题,真正的解决方案是确保在没有图像的情况下不渲染该元素,即添加检查!!item.images?.length。
| 归档时间: |
|
| 查看次数: |
2470 次 |
| 最近记录: |