Luau typechecking: Let me interpret a string as a type declaration

Right now, the Instance.new function has a behavior where it can interpret the string literal you give it and output a type that matches the input. I wanted that behavior for my create 'name' {props} function, and it appears that the best way to do that is by doing two ridiculous things:

  1. At the end of the create function, for every instance type, statically compare the original input string with a known instance name and then cast the return value to that instance.
  2. So that you aren’t doing 2000 string comps in your function body, recast your entire create function to a function that actually does those string comps.

image

The knowledge that this is in my codebase brings me great pain. I think the solution is a way to evaluate a static string as a type. For example,

return object :: interpret(source)

Which would simply statically evaluate whatever is in the arguments, like typeof, except instead of using the type of the argument it would interpret the argument as though it were statically declared.

return object :: TextLabel
-- is equivalent to
local staticString = "TextLabel"
return object :: interpret(staticString)
12 Likes

Please excuse this absolutely insane bump, but I think this feature should really be considered!

You could use this in conjunction with the new keyof type functions we got in the type solver beta to write something like this:

local function Create(class: string)
	return function(props: { [keyof<interpret(class)>]: any })
		-- code...
	end
end

…and get full autocomplete for its properties!
image
(I manually set the props to keyof<Part> to get this screenshot, but imagine if it actually worked automatically! We are so close!!)

This would also be really useful for libraries like Fusion or react-lua/Roact where you have to write out Instances properties in dictionaries.

2 Likes