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

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?

Answer1:

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

But you can overcome this via interfaces reengineering:

<ol> <li>

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; } </li> </ol>

Both C and B will be castable to BaseA.

<ol start="2"> <li>

Use optional field

interface A { a: number; x?: any; } interface B extends A { b: number; } interface C extends A { b: number; } </li> </ol>

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

Answer2:

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).

人吐槽 人点赞

Recommend

Comment

用户名: 密码:
验证码: 匿名发表

你可以使用这些语言

查看评论:Is it possible to remove an inherited field/method in a child class/interface?