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
For a lot of code duplication, its often helpful to destructure objects for later use. Type guards on switch/if help a lot in preventing unnecessary casts, but could be extended to infer a deeper understanding in some cases.
In doStuffDestructured, we can logically infer that because we destructured vehicle at a moment in time, that the types/values are tied together, just as we in doStuff.
At a minimum I would propose this works for const destructuring as you can make reasonable assumptions outside of function scope:
letvehicle: Car|Truck=getVehicle();const{type, something}=vehicle;functiondoStuffDestructuredOutOfScope(){switch(type){case"Car":
takesNumber(something);// error, not assignablebreak;case"Truck":
takesBoolean(something);// error, not assignablebreak;}}
It seems to follow that for destructuring with letoutside of scope means we cannot track if the values have been assigned to something else, but could technically support let destructuring within scope. Honestly, I think its too hard to reasonable about for most end users that only supporting this for const is reasonable.
switch here is a red-haring. the issue is that once a variable is destructured in an assignment, the compiler can not assert any relationships between the constituents..
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
For a lot of code duplication, its often helpful to destructure objects for later use. Type guards on switch/if help a lot in preventing unnecessary casts, but could be extended to infer a deeper understanding in some cases.
Lets use a trivial example:
In
doStuffDestructured
, we can logically infer that because we destructured vehicle at a moment in time, that the types/values are tied together, just as we indoStuff
.At a minimum I would propose this works for
const
destructuring as you can make reasonable assumptions outside of function scope:It seems to follow that for destructuring with
let
outside of scope means we cannot track if the values have been assigned to something else, but could technically supportlet
destructuring within scope. Honestly, I think its too hard to reasonable about for most end users that only supporting this forconst
is reasonable.Thanks
CC/ @Andy-MS @ahejlsberg @mhegazy @RyanCavanaugh
The text was updated successfully, but these errors were encountered: