monnef
monnef

Reputation: 4053

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?

Upvotes: 4

Views: 3742

Answers (3)

Lucas L Jordan
Lucas L Jordan

Reputation: 101

This can be achieved using typescripts omit type-keys noting that in typescript you can extend multiple interfaces at once.

Typescript omit:

Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).

Using your example:

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

interface B extends A {
  b: number;
}

interface C extends Omit<A, 'x'>, Omit<B, 'x'> {}

Returns:

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

Working Typescript Playground demo

Upvotes: 2

Sepehr
Sepehr

Reputation: 2111

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

Upvotes: 2

TSV
TSV

Reputation: 7641

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.

Upvotes: 3

Related Questions