父类的方法签名是不是都要使用@generic才能确保子类调用父类方法时能够返回子类型?但是这样又会失去父类型提示 #2640
Unanswered
xiangnanscu
asked this question in
Q&A
Replies: 4 comments 2 replies
-
这是没有使用generic的代码, 子类方法不能返回子类型 ---@class Vehicle
local Vehicle = {}
---@param self Vehicle
---@return Vehicle
function Vehicle:echo()
return self
end
---@param self Vehicle
---@return Vehicle
function Vehicle:drive()
self:echo()
return self
end
---@class Car:Vehicle
local Car = {}
local x = Car:drive() -- 这里x的类型是Vehicle, 但实际上应该是Car
|
Beta Was this translation helpful? Give feedback.
0 replies
-
还有个疑问 |
Beta Was this translation helpful? Give feedback.
0 replies
-
有个特殊返回类型叫self 你可以用---@return self |
Beta Was this translation helpful? Give feedback.
2 replies
-
試了一下可以對 ---@generic T: Vehicle
---@param self T|Vehicle
---@return T
function Vehicle:drive()
self.echo() -- 這裡就有提示了,也不影響最終的 return self 仍會按 generic type `T`
return self
end |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
比如父类
Vehicle:drive
方法, 为了确保子类Car调用drive能够返回Car类型, 我使用了generic如果确实是这样, 又会引出另一个问题:编写父类方法时就失去了父类的类型提示, 有办法解决吗?

Beta Was this translation helpful? Give feedback.
All reactions