Skip to content

Type narrowing in ternary operator not working correctly #2233

Open

Description

@felixhirt

How are you using the lua-language-server?

Visual Studio Code Extension (sumneko.lua)

Which OS are you using?

Windows

What is the issue affecting?

Type Checking

Expected Behaviour

In a ternary expression with type checking: "local a = type(x) == "something" and dosomething(x) or somethingelse(x)", the type should be narrowed for both cases

Actual Behaviour

The type is only narrowed for the first case (boolean here), in the second case it is still boolean or string
image

Reproduction steps

Copy the code

Additional Notes

No response

Log File

No response

Activity

  1. barrettruth commented on Apr 9, 2026

    @barrettruth

    For #2233 / #3154, I was able to replicate with:

    ---@param s string?
    local function takes_string(s) end
    
    ---@param x string|number?
    local function f(x)
        takes_string(type(x) == 'number' and tostring(x) or x)
    end

    I think the following MVP is appropriate:

    extend the current and RHS truthiness heuristic from literals to simple direct calls ONLY whose first documented return is definitely truthy.

    Scope:

    • include simple name() calls like tostring(x), but only when all visible definitions document a truthy first return
    • exclude helper-body inference, fallthrough analysis, chained lookups, etc.

    e.g. these are in scope:

    ---@return string
    local function as_string(v) end
    
    ---@param x string|number
    local function f(x)
        local y = type(x) == 'number' and as_string(x) or x
    end

    to me this was broader than a tostring()-only case but still conservative enough to avoid turning tracer into a second inference engine.

    @sumneko wdyt?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions