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
Generic types combined with & instead of |Β #48287
classExampleClass<T>{test(value: T): T{returnvalue;}}classExample1extendsExampleClass<String>{}classExample2extendsExampleClass<Number>{}functionExample(example: 1|2)// returns `typeof Example1 | typeof Example2`{returnexample===1?Example1:Example2;}constinstance=new(Example(1))();instance.test('');// ERROR: Argument of type 'string' is not assignable to parameter of type 'Number & String'
π Actual behavior
Combining classes with generic type results in generic types on arguments to be combined with &.
But get combined with | for return types.
Yes, because the first T is in an input position (contravariant) and the other is in an output position (covariant). If you have a function and the only thing you know about it is that it accepts either an X or a Y, and will throw if you give it the wrong thing, the only thing you can safely pass to it is X & Y, i.e. a value that satisfies both types. Thatβs what the error youβre seeing reflects.
Activity
whzx5byb commentedon Mar 16, 2022
This is a correct error. Here is a simple example in which your expected behavior is unsound:
See: #30769 for more details.
RoelVB commentedon Mar 16, 2022
I don't see how this would be correct.
In
test(value: T): Tthe firstTbecomesString & Number, the secondTbecomesString | Numberfatcerberus commentedon Mar 16, 2022
Yes, because the first
Tis in an input position (contravariant) and the other is in an output position (covariant). If you have a function and the only thing you know about it is that it accepts either an X or a Y, and will throw if you give it the wrong thing, the only thing you can safely pass to it isX & Y, i.e. a value that satisfies both types. Thatβs what the error youβre seeing reflects.RoelVB commentedon Mar 16, 2022
Thanks Bruce Pascoe (@fatcerberus), I understand now