Skip to content

Problem with methods of generic classes #3339

@Lukyn150

Description

@Lukyn150

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, Annotations

Expected Behaviour

  1. Define a generic base class Foo with a method function which returns the generic type
  2. Inherit from the base class and specify the generic type
  3. Use the method and expect the specified generic type on the output
---@class Foo<T>
---@field myValue T
local base = {}

---@return T
function base:get()
	return self.myValue
end

---@type Foo<number>
local ex1 = base --Use class directly
---@class Example2 : Foo<string>
local ex2 = ex1 --Start with a version with generic type specified
---@class Example3 : Foo<boolean>
local ex3 = base --Start with a version without the generic type specified

local I 	= ex1.myValue 	--Correct: number
local a 	= ex1:get() 	--Correct: number
local II 	= ex2.myValue 	--Correct: string
local b 	= ex2:get() 	--Correct: string
local III 	= ex3.myValue 	--Correct: boolean
local c 	= ex3:get() 	--Correct: boolean

Actual Behaviour

Attempting to expand the parent class directly displays a warning, (Example 3) but using a variable with specified type does not (Example 2).
The method defined in the parent class fails to infer the generic type from the child classes

---@class Foo<T>
---@field myValue T
local base = {}

---@return T
function base:get()
	return self.myValue
end

---@type Foo<number>
local ex1 = base
---@class Example2 : Foo<string>
local ex2 = ex1
---@class Example3 : Foo<boolean>
local ex3 = base --Cannot assign 'Foo' to 'Example3'

local I 	= ex1.myValue 	--Correct: number
local a 	= ex1:get() 	--Correct: number
local II 	= ex2.myValue 	--Correct: string
local b 	= ex2:get() 	--Incorrect: T
local III 	= ex3.myValue 	--Correct: boolean
local c 	= ex3:get() 	--Incorrect: T

Reproduction steps

  1. Define a generic base class with a method function which returns the generic type
  2. Inherit from the base class and specify the generic type
  3. Use the method and expect the specified generic type on the output

Additional Notes

No response

Log File

service.log

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions