1

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?

Ogen
  • 6,499
  • 7
  • 58
  • 124
  • 2
    Can you check again, for me it looks it is exactly what you want, – Maciej Sikora Mar 08 '20 at 21:03
  • 1
    This looks ok. Can you post the code where you get the error? – Aleš Doganoc Mar 08 '20 at 21:12
  • Please consider providing a [mcve] as described in [ask]. Right now [I cannot reproduce the issue](https://www.typescriptlang.org/play/#code/C4TwDgpgBAggRgYygXigIgIZqgH3XbPNBNAWACgKBLAO2AgCcAzDBaAMQHtO4MGB9AIz8ADFADeFKFCbcAQnwBcsRBQC+FanUYs2ULjz5ChEqTPlKVSIgBNC6CPbRMy5DZXIJONAM7AZyga8AsKCKKbk0rKcCgzKaI7qFF6+-gDmgdzBxmKo4uYxlmgEUGoA3MneflAAFpmGISaoALIYwDUAdAwYNDacALYAFACUUAA8UCIdAKxQAPxQaVDKTEA). Good luck! – jcalz Mar 09 '20 at 00:23
  • Sorry, I have updated my question to correctly show how it's going wrong. – Ogen Mar 09 '20 at 01:06
  • Does this answer your question? [Extending union type alias in typescript?](https://stackoverflow.com/questions/45745441/extending-union-type-alias-in-typescript) – Shlang Mar 09 '20 at 07:57

1 Answers1

1

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.

Maciej Sikora
  • 19,374
  • 4
  • 49
  • 50