Easier way to check types against runtime values
Forgive me if there's a prior Feature Request for this, I'd be surprised if there wasn't.
There should be an easier way to compare types with values.
type Vector = {
X: number,
Y: number
}
local function foo(A: unknown)
-- Refines "A" down to Vector past this point
assert(typeis(A, Vector))
-- ...
end
The current solution is to use code like:
local function foo(A: unknown)
assert(typeof(A) == "table")
assert(typeof(A.X) == "table")
assert(typeof(A.Y) == "table")
-- ...
end
, which can be cumbersome, especially during active development where types can change, forcing back-and-forth to keep the analysis and runtime validations in sync, or use a library like GreenTea.
Maybe this typeis function could be a special built-in that the compiler deconstructs to an actual function, unless there are plans to turn types into values in the future.
#1862 is a similar request for an annotation that would cause a parameter type to be enforced at runtime, but it's not technically the exact same request. To actually be added, this feature would definitely require an RFC in luau-lang/rfcs that actually covers the design in detail, especially the handling of function types which require a lot of care and depending on the design decisions you make can have a significant performance burden. It's likely the sort of project that our team would have to take on the design of first frankly, but it is on our radar as something that some folks care a lot about.
Thank you for the clarification. I wrote this request in a bit of a rush, but after reflecting on it a little I realize how much work there would need to be before reaching the stage I described. I only wrote "unless there are plans to turn types into values" sarcastically before, but I dunno, maybe that's the true path forward, some kind of type reflection. I was just compelled to make this after a discussion with a friend of mine on how inconvenient it was to correctly refine a union type between number and a custom composite down to just the latter for an __add metamethod.
(And also sending my well-wishes to the team on improving the stability of the New Type Solver :) )