Closed pouwelsjochem closed 1 year ago
Consider:
---@class MyClass
---@field type string
---@class ExtendedMyClassA : MyClass
---@field fieldA string
---@class ExtendedMyClassB : MyClass
---@field fieldB boolean
function createExtendedClassA()
return --[[---@type ExtendedMyClassA]] {
type = "Class A",
fieldA = "foo"
}
end
function createExtendedClassB()
return --[[---@type ExtendedMyClassB]] {
type = "Class B",
fieldB = true
}
end
---@type ExtendedMyClassA[]
arrayOfClassA = {
createExtendedClassA()
}
---@param arr MyClass[]
function injectClassB(arr)
table.insert(arr, createExtendedClassB())
end
injectClassB(arrayOfClassA)
for _, myClassA in ipairs(arrayOfClassA) do
print(myClassA.fieldA:sub(1))
end
Luanalysis is correctly reporting the error:
Which prevents (or rather highlights) the runtime crash:
However, you can still work with arrays that contain subtypes with the assistance of generics e.g. the following is just fine:
---@class MyClass
---@field type string
---@class ExtendedMyClassA : MyClass
---@field fieldA string
---@class ExtendedMyClassB : MyClass
---@field fieldB boolean
function createExtendedClassA()
return --[[---@type ExtendedMyClassA]] {
type = "Class A",
fieldA = "foo"
}
end
function createExtendedClassB()
return --[[---@type ExtendedMyClassB]] {
type = "Class B",
fieldB = true
}
end
---@type ExtendedMyClassA[]
arrayOfClassA = {
createExtendedClassA()
}
---@type ExtendedMyClassB[]
arrayOfClassB = {
createExtendedClassB()
}
---@type MyClass[]
arrayOfMyClass = {
createExtendedClassA(),
createExtendedClassB()
}
---@generic T : MyClass
---@param arrayOfMyClass T[]
function doSomethingWithMyClassArray(arrayOfMyClass)
for _, myClass in ipairs(arrayOfMyClass) do
print(myClass.type)
end
end
doSomethingWithMyClassArray(arrayOfClassA)
doSomethingWithMyClassArray(arrayOfClassB)
doSomethingWithMyClassArray(arrayOfMyClass)
Ah I see the problem with that, thank you for elaborating the possible issues with my suggestion solution. Using generics is the way to go then :)
Environment
Lua
Type Safety
What are the steps to reproduce this issue?
What happens?
When assigning a
ExtendedMyClass[]
to a variable withMyClass[]
type there's an error saying:Type mismatch. Required: 'MyShape[]' Found: 'ExtendedMyShape[]
. This works fine when its not an array and we're just assigning aExtendedMyClass
to a variable withMyClass
type.What were you expecting to happen?
No error to be given when assigning
ExtendedMyClass[]
toMyClass[]
since this works on non-array variables already andExtendedMyClass
should include all properties that exist onMyClass
.