簡體   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