首页 > 解决方案 > 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 属性的对象或布尔值。

标签: reactjstypescript

解决方案


第一个问题是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:

事实证明,attachmentsin 中的属性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;

推荐阅读