使用一个接口的一部分在另一个接口中的最佳方法

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

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&lt;IAccordion, &#39;isMultiple&#39; | &#39;itemClassName&#39;&gt; {
    accordionItem: IAccordion[&#39;accordionItems&#39;][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[&#39;accordionItems&#39;][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&lt;IAccordion, &#39;isMultiple&#39; | &#39;itemClassName&#39;&gt; {
    accordionItem: AccordionItem;
    isActive: boolean;
}

huangapple
  • 本文由 发表于 2023年2月24日 17:37:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554889.html
匿名

发表评论

匿名网友

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

确定