英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论