问题
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:
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.
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