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 types in generics do not correctly check types.Β #46552
interfaceTwoSameTypes<T>{a: T;b: T;}// @ts-expect-errorconstx : TwoSameTypes<Number|String>={a: 1,b: "string",// <-- This does not give an error, because `b` has the type `String | Number`}
π Actual behavior
No error happens
π Expected behavior
I would expect an error for the value of x because both a and b are expected to have the same type, but they don't in this case.
For the record, and as can be seen from the playground link, when doing TwoSameTypes<Number> | TwoSameTypes<String> instead of TwoSameTypes<Number | String> we do end up with the desired behaviour. But I think these two different ways of defining are equivalent? So it seems like the latter way of doing it should work as well.
Furthermore, here's demo of a use case for this behaviour. I would like to use keyof ValueMap as the generic type, so I don't have to type every possible enum twice.
Apologies in advance if this is a duplicate, I wasn't able to find the right keywords to describe this behaviour.
a and b do have the same type though; and that type is number | string. TwoSameTypes<number> | TwoSameTypes<string> and TwoSameTypes<number | string> are not equivalent, and this is the difference.
Activity
nmain commentedon Oct 27, 2021
aandbdo have the same type though; and that type isnumber | string.TwoSameTypes<number> | TwoSameTypes<string>andTwoSameTypes<number | string>are not equivalent, and this is the difference.You can get the desired behavior here with distributive conditional types: https://www.typescriptlang.org/play?ts=4.4.4#code/JYOwLgpgTgZghgYwgAgGpwDYFcIFk4AOyA3gFACQIWAtgFzIByNARtANwUDOYU9Ayj1ABzDgF9SEsAE8CKAGIB7BQB4AKgD5kAXmSrkEAB6QQAE07IA1hCkKYaTDnxEA-CQrTZ9VR3IA3TPTo2HiEANqqALpiyPQgEL7sEgD0ScigkLCI8kpq+kYQpuZWNnZBjoSaZCnI5B4QXhzVfgH2wU7hUaTV4qR1yLgQYAAWCiYAgtrIiioARFTUM5oAPlM5M9xQixx9A8OjAEKT08pzNDPIK+s8W70yKLsjJgDCRznFtq3lBOocXakAAmBOABaQyyBBgUFQKAKKCkBAKEDcZAGGL9QaPCY6Mi1O70U4LAA0FH8GHx0BhUAAhDNCchqspgcDdENgOYhMAEuY4CB9NDYXS4OYwRAIRATKQetVASCRRCoZT4YjkVI0Q8DpMcXV8fNaSSWjMKbCaXSGUyWWzkCYFBBzCAFGBkByEsgeXzKXTWAg4FhOCgAAak-3IIZC5DDFB9f0CKDCC6MFjQf2S5IAoGggzgyFGuEIpGOgBeaoxoxe2PceOQBL1zTJVZzJvpqUZzNUrO5GE4CitNs4IAA5I7nSg3TnkDBYeGhihOHBqCgoBAhYiU0A
jespertheend commentedon Oct 27, 2021
Ah sorry, I wasn't aware this was intentional. Thanks for example!