Not-Nil-narrowing a field, is it possible? #3249
Unanswered
ipsquiggle
asked this question in
Q&A
Replies: 2 comments 3 replies
-
AFAIK this is indeed the limitation of the current type system, in which a table field cannot be auto type narrowed in if branch. If you are unwilling to change the code structure
local target_count
if config.count then
target_count = config.count
else
target_count = ... -- fancy logic here that returns an integer
end
---@cast target_count -nil ### means remove the `nil` type
target_count --> now this will be `integer` only
local target_count
if config.count then
target_count = config.count --[[@as integer]]
else
target_count = ... -- fancy logic here that returns an integer
end
target_count --> now this will be `integer` only the |
Beta Was this translation helpful? Give feedback.
1 reply
-
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have code that looks like this. The problem is that
config.count
is not being narrowed so target_count is considered possibly nil.I can write it this way instead, and get a correctly not-nil type.
I'm guessing this is just a limitation of the type system, so my question is: Is there something else I could do to make this work more smoothly? Copying into a local is really unfortunate, I'd rather not change the structure of the code just to satisfy the type checker, so I might be SOL but can anyone suggest a way of writing this so that target_count is non-nil?
To be clear, the logic in the second branch is not trivial, I'm not just looking for a way to turn this into a oneliner.
Thanks.
Beta Was this translation helpful? Give feedback.
All reactions