英文:
The best approach using part of an interface in another interface
问题
在IAccordionItem接口中,accordionItem属性与IAccordion中的accordionItems属性相似,但它是一个单独的对象。我想知道这行代码的最佳选项是什么:
accordionItem: IAccordion['accordionItems'][0];
最佳选项是将accordionItem属性指定为IAccordion接口中的accordionItems数组的第一个元素。这行代码的目的是将IAccordionItem中的accordionItem属性与IAccordion中的accordionItems数组的第一个元素关联起来。
英文:
I have a project with nextjs and typescript. I have two interfaces like below
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
export interface IAccordion {
accordionItems: {
id: string | number;
title: string | React.ReactElement;
content: string | React.ReactElement;
}[];
isMultiple?: boolean;
className?: string;
itemClassName?: string;
}
export interface IAccordionItem
extends Pick<IAccordion, 'isMultiple' | 'itemClassName'> {
accordionItem: IAccordion['accordionItems'][0];
isActive: boolean;
}
<!-- end snippet -->
in IAccordionItem I have accordionItem property that is like the accordionItems property in IAccordion but it is a single object I want to khow is this line of code
accordionItem: IAccordion['accordionItems'][0];
the best option that I have
答案1
得分: 1
你使用 Items[0] 的方法是有效的。建议使用 Items[number] 也可以。或者我建议将可重复使用的实体提取到自己的类型/接口中,并赋予一个易于理解的名称。这样,如果需要,现在和将来都更容易重用和维护。
interface AccordionItem {
id: string | number;
title: string | React.ReactElement;
content: string | React.ReactElement;
}
export interface IAccordion {
accordionItems: AccordionItem[];
isMultiple?: boolean;
className?: string;
itemClassName?: string;
}
export interface IAccordionItem
extends Pick<IAccordion, 'isMultiple' | 'itemClassName'> {
accordionItem: AccordionItem;
isActive: boolean;
}
英文:
You approach with Items[0] is a working one. The suggested Items[number] will also work. Alternatively I would suggest extracting the reusable entities into its own type/interface with a human readable name. This way it will be easier to reuse and maintain. now and later if needed.
interface AccordionItem {
id: string | number;
title: string | React.ReactElement;
content: string | React.ReactElement;
}
export interface IAccordion {
accordionItems: AccordionItem[];
isMultiple?: boolean;
className?: string;
itemClassName?: string;
}
export interface IAccordionItem
extends Pick<IAccordion, 'isMultiple' | 'itemClassName'> {
accordionItem: AccordionItem;
isActive: boolean;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论