Is it possible to remove an inherited field/method in a child class/interface?

China☆狼群 提交于 2019-12-24 09:51:24

问题


Something along these lines:

interface A {
  a: number;
  x: any;
}

interface B extends A {
  b: number;
}

interface C {
  a: number;
  b: number;
}

So the B would be equal to C (omitting field x but still extending A). Is it possible? If so, how?


回答1:


It is impossible to remove an inherited field/method of an interface in TypeScript.

But you can overcome this via interfaces reengineering:

  1. Extract base interface

    interface BaseA {
      a: number;
    }
    
    interface A extends Base A {
      x: any;
    }
    
    interface B extends A {
      b: number;
    }
    
    interface C extends BaseA {
      b: number;
    }
    

Both C and B will be castable to BaseA.

  1. Use optional field

    interface A {
      a: number;
      x?: any;
    }
    
    interface B extends A {
      b: number;
    }
    
    interface C extends A {
      b: number;
    }
    

I'm sure there are other ways depending on the certain task context.




回答2:


here is another hacky way to deal with deleting child interface members:

interface Base {
  a: number;
  x?: any;
}

interface Child extends Base {
  x?: undefined;
}

this way, either the field x should not exist at all or if it does, it must be set to undefined which is as good as non-existent in most cases (unless you are trying to enumerate class members or do things like that).



来源:https://stackoverflow.com/questions/41671281/is-it-possible-to-remove-an-inherited-field-method-in-a-child-class-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!