Ogen
Ogen

Reputation: 6709

Extend an interface which has a property that is a set of values

I have this interface:


type Abc = "a" | "b" | "c"

interface Foobar_1_0 {
  fooBar: Abc;
  otherProp: number;
}

interface Foobar_1_1 extends Foobar_1_0 {
  fooBar: Abc | "d" | "e" | "f"
}

My desire is to have Foobar_1_1's foo property to be one of a, b, c, d, e, f, and to have the inherited otherProp via extension. However, it is not working, how can I achieve this?

Upvotes: 1

Views: 63

Answers (1)

Maciej Sikora
Maciej Sikora

Reputation: 20162

The issue you are facing is that Foobar_1_1 is not a subset of Foobar_1_0 because property fooBar in the Foobar_1_1 is wider type then the original type has. With union types subset is something which has the same amount or less variants. So for example a | b is subset of a | b | c, but in your case it is another way round. Consider the proof:

type ExtendsAbc = Abc | "d" | "e" | "f" extends Abc ? true : false 
// false it doesn't extend

Above clearly says your type is not extending the original one, and that is why the error happens.

In order to have all properties extended, but make property fooBar wider type we can omit this property during extending by Omit utility type, consider:

interface Foobar_1_1 extends Omit<Foobar_1_0, 'fooBar'> {
  fooBar: Abc | "d" | "e" | "f"
}

Now the interface works and fooBar property is able to not extend the fooBar from Foobar_1_0.

Upvotes: 1

Related Questions