Skip to content

Variable should not be inferred as string just because it's concatenated with one #680

Description

@ArcanoxDragon

Describe the bug
If I declare a variable and put a ---@type Whatever comment on it marking it as a Whatever-typed variable, and then later concatenate that variable with a string, the IDE thinks the variable is typed as string|Whatever, even if Whatever has a __concat metamethod. I'm not necessarily asking for analysis of metatables/methods, but if I have a variable that's explicitly marked as being a specific type, concatenating it with a string shouldn't widen it to string|Whatever, as it doesn't need to be a string to be concatenated with one.

To Reproduce
Steps to reproduce the behavior:

  1. Create a Lua file with my sample script below
  2. Hover over the test variable declared in TestClass:new
  3. See incorrectly widened type hint
---@class TestClass
---@field name string
local TestClass = {}
TestClass.__index = TestClass

function TestClass:new(name)
    ---@type TestClass
    local test = { name = name }
    
    setmetatable(test, TestClass)
    
    print("Created test class " .. test .. "!")
        
    return test
end

function TestClass.__concat(lhs, rhs)
	if type(lhs) == "string" then
		return lhs .. rhs.name
	elseif type(rhs) == "string" then
		return lhs.name .. rhs
	end
	return nil
end

Expected behavior
The test variable should still be typed as Whatever despite being concatenated with a string.

Screenshots
image

Environment (please complete the following information):

  • OS: Windows 10 21H1
  • Is WSL remote? No
  • Client: VSCode 1.60.1

Provide logs
https://hastebin.com/atuyasuzup.log

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingfeat/LuaCats AnnotationsRelated to Lua Language Server Annotations (LuaCats)

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions