You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Union of types contains only the keys that exist in both subtypes #35224
I see some inconsistency in the type system regarding union types. In my opinion the current implementation is quite confusing. Please see the example below.
/* EXAMPLE 1 - keyof accepts optional fields */interfaceType{requiredField: string;optionalField?: string;}consttest=(key: keyofType)=>{};test('requiredField');// keyof accepts required fields (of course)test('optionalField');// but also optional fields (makes sense)/* EXAMPLE 2 - keyof does not accept optional fields from union type */interfaceSubtype1{commonField: string;}interfaceSubtype2{commonField: string;uniqueField: string;}typeSupertype=Subtype1|Subtype2;consttest2=(key: keyofSupertype)=>{};test2('commonField');// this is accepted (like line 9)test2('uniqueField');// then why this is not accepted (like line 10)?
Output:
This line fails:
test2('uniqueField');
Expected behavior:
This line compiles fine:
test2('uniqueField');
In my understanding, Supertype type defined above should evaluate to something like:
Whereas, from the playground example, we can see that it evaluates to:
interface Supertype {
commonField: string;
}
I would not expect that. Can you please explain the reasoning behind such behavior? Sorry for the trouble, I imagine that is a design choice, but I did not find any source on why it is implemented like so.
Here's a relevant StackOverflow answer regarding union types. With a union type you only get access to what is known to be present in both types. uniqueField is not present in Subtype1.
In my understanding, Supertype type defined above should evaluate to something like:
SuperType is not equivalent to SubType1 | SubType2 because the former can have uniqueField1 but not uniqueField2, while the latter either has both or none.
Activity
MartinJohns commentedon Nov 20, 2019
Here's a relevant StackOverflow answer regarding union types. With a union type you only get access to what is known to be present in both types.
uniqueFieldis not present inSubtype1.But that would be wrong. For example if you have this interface:
This type is compatible to
Subtype1, and as a result toSubtype1 | Subtype2, but it is not compatible to theSupertypeI quoted from you.jack-williams commentedon Nov 20, 2019
This is only valid when there is a one property delta, but it doesn't work generally.
SuperTypeis not equivalent toSubType1 | SubType2because the former can haveuniqueField1but notuniqueField2, while the latter either has both or none.mc-suchecki commentedon Nov 25, 2019
Thank you for your answers! That clarifies the problem for me, I will close the issue.