devcat-studio / kailua

🌴 Type Checker and IDE Support for Lua
https://devcat-studio.github.io/kailua/
Apache License 2.0
167 stars 5 forks source link

How to denote generic function that cast from parent class to child class? #6

Open JamesKim2998 opened 7 years ago

JamesKim2998 commented 7 years ago

I'm now trying to cast parent class(Component) to child class(WeaponComponent).

So I made function cast_to_weapon,

Component = class()
WeaponComponent = class()
--v function(parent: Component) --> WeaponComponent
function cast_to_weapon(parent)
    --# assume parent: WeaponComponent
    return parent
end

But as you can see, it's hard to reuse. Because, source type only can be Component, and destination type only can be WeaponComponent...

So I want to denote this like below,

--function(parent: Parent, childType: typeof(Child)) -> Child where Child extends Parent
function cast_to(parent, childType)
    return type
end

local parent = Component.new()
local child = cast_to(parent, WeaponComponent)

How can this be possible?