Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function Prototype Narrowing with nils #2707

Open
Rathoz opened this issue Jun 12, 2024 · 2 comments
Open

Function Prototype Narrowing with nils #2707

Rathoz opened this issue Jun 12, 2024 · 2 comments

Comments

@Rathoz
Copy link
Contributor

Rathoz commented Jun 12, 2024

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

Foo.Bar('Baz', 'Qux') -- **string**
Foo.Bar('Baz', nil) -- nil
Foo.Bar('Baz') -- nil
Foo.Bar(nil, 'Qux') -- nil
Foo.Bar(nil, nil) -- nil
Foo.Bar() -- nil

Actual Behaviour

Foo.Bar('Baz', 'Qux') -- **string|nil**
Foo.Bar('Baz', nil) -- nil
Foo.Bar('Baz') -- nil
Foo.Bar(nil, 'Qux') -- nil
Foo.Bar(nil, nil) -- nil
Foo.Bar() -- nil

Reproduction steps

---@param baz string|number
---@param qux string|number
---@return string
---@overload fun(text: string|number, title: nil):nil
---@overload fun(text: nil, title: string|number):nil
---@overload fun(text: nil, title: nil):nil
function Foo.Bar(baz, qux)
	if not baz or not qux then
		return nil
	end
	return 'SomeString'
end

Additional Notes

It seems to match the 'strings' can be nil

First input example
image

Last input example
image

Log File

No response

@tomlau10
Copy link
Contributor

Just did some testings, seems need to add a ? when declaration a function param to be of nil type 😕
Then LuaLS can type narrow the function signature correctly:

---@param baz string|number
---@param qux string|number
---@return string
---@overload fun(text: string|number, title?: nil):nil ### add `?` to `title`
---@overload fun(text?: nil, title: string|number):nil ### add `?` to `text`
---@overload fun(text?: nil, title?: nil):nil ### add `?` to both `text` and `title`
function Foo.Bar(baz, qux)
    if not baz or not qux then
        return nil
    end
    return 'SomeString'
end

local a = Foo.Bar('Baz', 'Qux') -- **string** => it's corrects now
local a = Foo.Bar('Baz', nil) -- nil
local a = Foo.Bar('Baz') -- nil
local a = Foo.Bar(nil, 'Qux') -- nil
local a = Foo.Bar(nil, nil) -- nil
local a = Foo.Bar() -- nil

@Rathoz
Copy link
Contributor Author

Rathoz commented Jun 13, 2024

Interesting workaround 🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants