Merge Two Interfaces

后端 未结 3 1760
长发绾君心
长发绾君心 2020-12-05 09:32

Seeking confirmation or clarification

If I have two interfaces. What is the \"proper\" way to create a merge of those two interfaces.

Foo

IF         


        
相关标签:
3条回答
  • 2020-12-05 09:45

    If you're wanting to merge 2 interfaces which contain members more than 1 level deep:

    export interface TypeOne  {
      one: {
        two: {
          hello: string;
        }[]
      }
    }
    
    export type TypeTwo = {
      one: {
        two: {
          world: string;
        }[]
      }
    } & TypeOne;
    
    const x: TypeTwo;
    x.one.two[0]. // autocompletes options are 'hello' / 'world'
    
    0 讨论(0)
  • 2020-12-05 09:54

    This article explains the relation between interfaces and type aliases very well, this part is focused on small differences between them.

    Both

    interface IFooBar extends IFoo, IBar {}
    

    and

    type IFooBar = IFoo & IBar;
    

    are common ways to do this and will behave identically in most cases. Since type takes less characters to type, it could be chosen for that reason.

    The inconsistency that is caused by mixed interface and type shouldn't be a problem; they are just suitable features to achieve the goal. If const BarClass = FooClass does the job, class BarClass extends FooClass {} shouldn't be preferred just because its consistently uses class everywhere (this example is used for illustrative purposes, there's a considerable difference between these approaches).

    Even though interface and type can behave similarly, there is a difference in case of merged interface (also covered in linked article). This will work:

    interface FooBar extends IFoo, IBar {}
    class FooBar { ... }
    

    And this will cause type error:

    type FooBar = IFoo & IBar;
    class FooBar { ... }
    
    0 讨论(0)
  • 2020-12-05 09:58

    I think there it is ok, or not ok relating to what meaning of the merged interface. If IFooBar is a new entity from perspective of object-oriented design, then empty interface is all right. But if there is no such entity, but you want just merge some unrelated interfaces (for some hacky code) - then just use IFoo & IBar in variable type definition, or type for shortening this.

    It's just my opinion as programmer, that came from object oriented languages like C++ and C#.

    0 讨论(0)
提交回复
热议问题