reactjs - Object 或 Boolean 如何在 Typescript 中声明类型
问题描述
在 React 中遇到了这种类型声明问题。
interface MessageCardProps {
message: {
id: string;
title: string;
content: string;
attachments: string[];
interest_count: number;
};
}
const MessageCard: FC<MessageCardProps> = ({
message: { id, title, content, attachments, interest_count },
}) => {
// ERROR: Type 'string | false' is not assignable to type 'boolean | { url: string; }'.
const image: { url: string } | boolean =
attachments.length > 0 ? attachments[0] : false;
return (
{/* Property 'url' does not exist on type 'true | { url: string; }'.*/}
{image && <img className={style.img} src={image.url} alt="timeline" />}
);
};
export default MessageCard;
声明类型的正确方法是const image
什么?它可以是具有 URL 属性的对象或布尔值。
解决方案
第一个问题是attachments[0]
它将返回一个字符串,而不是具有url
属性的对象。所以你可以使用 type string | boolean
。是否有特定原因要将其包装在对象中?
如果你使用string | boolean
,你可以做src={image}
编辑:
您甚至可以通过根本不使用布尔值并使用null
虚假值这一事实来进一步改进这一点。然后你可以这样做。
const image: string = attachments.length > 0 ? attachments[0] : null;
return (
{image && <img className={style.img} src={image} alt="timeline" />}
);
编辑2:
事实证明,attachments
in 中的属性MessageCardProps
不应该是字符串数组,而是具有名为“URL”的属性的对象数组。所以它应该是这样的:
interface MessageCardProps {
message: {
id: string;
title: string;
content: string;
attachments: {URL: string}[];
interest_count: number;
};
}
现在,要获取第一张图片,您可以这样做:
const image: string = attachments.length > 0 ? attachments[0].URL : null;
推荐阅读
- unix - 使用 sendmail 功能 unix 发送邮件时,文本附件的内容为空白
- javascript - “@arction/lcjs”错误报告:无法将单个切片添加到类型为“LabelsOnSides”的饼图中
- json - Swift:帮助解决'键路径值类型'_'无法转换为上下文类型'_''
- javascript - 数组字符串的字谜
- java - 使 JButton 周围的边框变大
- java - 6982:不满足安全条件
- jquery - 如果没有任何值,则 Jquery 添加值输入文本
- regex - 如何调整这个正则表达式以不知道键值对的顺序
- thread-local - 我们可以在 ThreadLocal 中存储多少个对象
- android - Proguard 在 android 中禁用 R8 后显示 moshi 的一些问题