TypeScript字典和列表的类型

huangapple go评论60阅读模式
英文:

Typescript Type of a dictionary and a list

问题

The first code defines a type of props using an object structure with curly braces {}, while the second code defines it using square brackets []. The difference is in how the reference property is defined:

In the first code:

reference?: 
  {
    title: string;
    link: string;
  }[];

reference is defined as an array of objects where each object has properties title and link.

In the second code:

reference?: [
  {
    title: string;
    link: string;
  }
];

reference is defined as an array containing a single object with properties title and link.

The first code allows for an array of objects for the reference property, while the second code expects an array containing only one object for reference. The difference lies in the structure of the reference property.

英文:

What's the difference between the codes below about defining a type of props

I found out the first one didn't give me a type error, but i don't know why the second code I had written first was wrong. For me, it seems like pretty make sense.


type Props = {
  reason: {
    id: number;
    title: string;
    description: string;
    reference?: 
      {
        title: string;
        link: string;
      }[];
  };
};

and


type Props = {
  reason: {
    id: number;
    title: string;
    description: string;
    reference?: [
      {
        title: string;
        link: string;
      }
    ];
  };
};

答案1

得分: 1

错误的原因是reference属性的类型不同。在第一个Props中,reference是一个数组,格式如下:

{
   title: string;
   link: string;
}

然而,在第二个Props中,你定义了一个元组而不是数组,这意味着它只包含一个元素。

英文:

The reason for the error is the type of the reference property. In the first Props the reference is an array of

{
   title: string;
   link: string;
}

However, in the second Props you define a tuple, not an array, which means that it contains only 1 element

huangapple
  • 本文由 发表于 2023年5月6日 20:08:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定