luau icon indicating copy to clipboard operation
luau copied to clipboard

Multiple return tuples on functions

Open metatablecat opened this issue 2 years ago • 1 comments

Right now, you can only define a singular return type on a function

function pcall<A..., R...>(f: (A...) -> R..., msg: string) -> (boolean, R...)

The issue here, especially with pcall, which is why I used it as an example, is that you cant control what tuple is returned, you can only create a union of one return, when sometimes, you'd want it to return a different tuple based on a literal value, for example with pcall again:

R... only if the first value is true string only if the first value is false

This helps with type narrowing since we know that if the pcall worked, we get R..., otherwise we get a string

I suggest the following type syntax for declaring tuple return unions

function f() -> (T1, T2) | (T1, T3)

as an example:

function pcall<A..., R...>(f: (A...) -> R..., msg: string) -> (true, R...) | (false, string)

metatablecat avatar Jun 16 '23 04:06 metatablecat

This would be super useful, I find myself going out of my way to have functions return tagged unions just to typecheck properly when what I really want to do is the above example

centau avatar Jun 22 '23 08:06 centau