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 understand that types are not kept narrowed inside callbacks because the narrowing could in general not hold anymore in there, however there are some "simple" scenarios where we can be sure that the narrowing holds, for example:
This scenario is a sort of a simple edge case of the general problem because:
The maybe variable holds a primitive value, so it will be passed to other functions by copy, so those functions outside the closure can't change its value inside the closure.
The code executed before the console.log call is done forever, since it doesn't have any callbacks that assign to maybe, and it's not wrapped in an unterminated loop.
The "code" after the console.log call also has no assignments to "maybe", in fact it has no references to "maybe" at all.
Under these conditions it's impossible for narrowing the type inside our function in the example above to be wrong, so it should be preserved.
Preserving narrowing in simple cases like the one mentioned above is very handy and allows the user to write clean code in more scenarios.
The text was updated successfully, but these errors were encountered:
fabiospampinato
changed the title
Support narrowing type inside closure in some simple cases
Support preserving type narrowing inside closures in some simple cases
Aug 27, 2023
Possibly, in some of those 450 comments π That sounds like a general umbrella issue though, maybe we need a smaller issue for this one "easily" addressable part of the problem.
π Search Terms
β Viability Checklist
β Suggestion
I understand that types are not kept narrowed inside callbacks because the narrowing could in general not hold anymore in there, however there are some "simple" scenarios where we can be sure that the narrowing holds, for example:
This scenario is a sort of a simple edge case of the general problem because:
maybe
variable holds a primitive value, so it will be passed to other functions by copy, so those functions outside the closure can't change its value inside the closure.console.log
call is done forever, since it doesn't have any callbacks that assign tomaybe
, and it's not wrapped in an unterminated loop.Under these conditions it's impossible for narrowing the type inside our function in the example above to be wrong, so it should be preserved.
π Motivating Example
Playground: https://www.typescriptlang.org/play?#code/FAMwrgdgxgLglgewgAhAhyAUBKZBvYYZZAGwFMZkBbAQwE8AjMgLmQGcYAnOCAc2QA+yCGBIkA3IWK1GZZAF5kAcjQIlkosihI2CcgDoSCfpiy55APnxTi1ek0m3kAemfIAegH4bAX2zjiQh9gIA
π» Use Cases
Preserving narrowing in simple cases like the one mentioned above is very handy and allows the user to write clean code in more scenarios.
The text was updated successfully, but these errors were encountered: