繁体   English   中英

Object 或 Boolean 如何在 Typescript 中声明类型

[英]Object or Boolean how to declare type in 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 属性的 object 或 boolean。

第一个问题是attachments[0]将返回一个字符串,而不是具有url属性的 object。 所以你可以使用类型string | boolean string | boolean 是否有特定原因要将其包装在 object 中?

如果你使用string | boolean string | boolean ,你可以做src={image}

编辑:

您甚至可以通过根本不使用 boolean 并使用null是一个虚假值这一事实来进一步改进这一点。 然后你可以这样做。

const image: string = attachments.length > 0 ? attachments[0] : null;

return (
  {image && <img className={style.img} src={image} alt="timeline" />}
);

编辑2:

事实证明, MessageCardProps中的attachments属性不应该是字符串数组,而是具有名为“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;

我猜您希望仅在设置了附件 [0] 时才设置图像?

如果是的话,我会这样输入。 (有最快和更简单的方法,但是这段代码使用了类型和类型的联合):

const attachments:Array<string> = ["/test"]

interface IImage {url:string | boolean }
const image : IImage  = attachments.length > 0 ? {url:attachments[0]} : {url:false}}

return(

        {image && typeof image.url==='string' && image.url!=="" && (<p>I have a valid url</p>)}

)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM