-
-
Notifications
You must be signed in to change notification settings - Fork 351
@return支持多种类型 #1583
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
Labels
enhancement
New feature or request
Comments
方案2没法给返回值写名字与描述 |
我突然发现@overload已经能实现多返回类型,结合近段时间的思考,建议如下: --同一签名对应多个返回类型的时候,@overload需要重复写相同的fun(a:string)签名,
--如果签名本身就比较复杂,一大坨那种,就会显得冗余
--此时方案一@return ()|()应该能够解决这个问题
---@param a string
---@return string
---@overload fun(a:string):number
---@overload fun(a:string):table
local function foo(a)
if a == 'a' then
return 'a'
elseif a == 'b' then
return 1
else
return {}
end
end
--签名和返回类型是一一对应关系的时候,@overload能够派上用场,但返回类型推断的精度还有提升空间
---@param a string
---@return string
---@overload fun(a:number):number
---@overload fun(a:table):table
local function foo(a)
if type(a) == 'string' then
return 'a'
elseif type(a) == 'number' then
return 1
else
return {}
end
end
local n = foo(123) --此时n只能为number
|
其实目前重新关注这个问题是预研变量关联的实现,目前的初步想法是: ---@tuple xxx.success
---@return true
---@return table result
---@tuple xxx.failed
---@return false
---@return string errMsg
---@return xxx.success | xxx.failed
local function xxx() end
local ok, res = xxx()
if not ok then
print('error:' .. res)
return nil
end
return res |
大佬相当于用@tuple标记分组, 把多种返回类型写到一个xxx名称空间里面,简洁明了, 兼顾了多种需求. 专业! |
@sumneko 这个要实现了吗大佬? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
两个方案,大佬参考:
方案一采用语法
@return ()|()|()
这种方案二,其实我觉得这种更直观,也便于书写
现在的设定,下面两种定义是等效的
可见,通过逗号表达式,一条@return语句就可以表达多个值类型,多条连续的@return语法应该留给更重要的多返回类型语法!优雅,简洁!个人愚见,仅供参考
The text was updated successfully, but these errors were encountered: