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
I expect that the code works but the last line results in compilation error:
Argument of type '{ a: number; b: number; }' is not assignable to parameter of type '{ a: number; b: number; } & { a: number; b: number; c: number; }'.
Property 'c' is missing in type '{ a: number; b: number; }' but required in type '{ a: number; b: number; c: number; }'.ts(2345)
The variable o implicitly gets the wrong { a: number; b: number; } type instead the correct { a: number; b: number; c: number; }.
It's basically nonsensical to intersect a tuple type with a variable-length array type; did you mean to write this instead?
interfaceType{obj: {a: number,b: number}[];}
The error is correct; if you took [] (a valid typeof ret) and "intersected" it with [{ a: 0, b: 0 }] (a valid Type["obj"], then the 0th element would lack a c property.
The issue here is that intersections of the form T[] & U[] aren't equivalent to (T & U)[]; this is a correct interpretation of the intersection operator because, for example, arr.push(T) is a valid operation on T[] but not a valid operation on (T & U)[]. Methods of intersections are exposed as naive overloads and order matters in this case because the first matching overload is picked for the purposes of contextual typing. It's not clear what better alternative would even exist without special-casing everything about arrays.
Activity
RyanCavanaugh commentedon Oct 2, 2019
It's basically nonsensical to intersect a tuple type with a variable-length array type; did you mean to write this instead?
The error is correct; if you took
[](a validtypeof ret) and "intersected" it with[{ a: 0, b: 0 }](a validType["obj"], then the 0th element would lack acproperty.asfernandes commentedon Oct 2, 2019
Yes, sure. Typo to create small reproducable test case. I edited it.
Note that type of
t(viewing in vscode) isAnd all of this is valid:
So
t.obj.map(o => f3(o))should be valid.asfernandes commentedon Oct 2, 2019
It's also interesting that it works if you change
to
But that does not change in all situations.
RyanCavanaugh commentedon Oct 17, 2019
The issue here is that intersections of the form
T[] & U[]aren't equivalent to(T & U)[]; this is a correct interpretation of the intersection operator because, for example,arr.push(T)is a valid operation onT[]but not a valid operation on(T & U)[]. Methods of intersections are exposed as naive overloads and order matters in this case because the first matching overload is picked for the purposes of contextual typing. It's not clear what better alternative would even exist without special-casing everything about arrays.