I am currently creating a constructor to create a lot of different types of objects similar to Instance.new().
I would like so when you start typing in a class name, the auto fill thing pops up, again similar to Instance.new().
I know I can do something similar like this:
function table.new(Classname: "Class" | "Other Class")
except with that, I’d have to put every class in their individually which can be a hassle, so is there anyway to speed this process up? Or is this the only method I can use?
With the current typesolver there’s not really a great way to do this. However, if you enable the new typesolver beta you can use something like keyof to get your desired result:
local thingNames = {
["ThingA"] = true,
["ThingB"] = true,
["ThingC"] = true,
}
local function foo(thing: keyof<typeof(thingNames)>)
print(thing)
end
tried this out, when I call the function, the autocomplete just shows that thing is a boolean, or when I set the values to strings, it just says string.
The closest you could get to a type inheriting properties is with nested types.
type Type<T> = {
someVal: T,
someOtherVal: 3
}
type Nested = {
a: 3
}
type Inherited = Type<Nested>
--> should now be inferred as:
--[[
{
someVal: {a: 3}
someOtherVal: 3
}
]]
As far as I’m aware, there’s not currently a way to do dynamic return types and have them properly inferred. There might be a way if you can write a type function for it. But, EgoMoose’s solution should work… I just tried it myself with this code and it worked fine:
local Types = {
Thing1 = true,
Thing2 = true
}
local function a(v: keyof<typeof(Types)>)
if (v == "Thing1") then
elseif (v == "Thing2") then
end
end
Ok I tried again, and it appears to be working now.
Ill set egomooses reply as the solution cause well, they said it first.
Anyhow I just noticed that for whatever reason, the type solver isnt displaying any functions when you try to call them with :, Any idea as to why this is happening?
If you’re defining them with :, that’ll be why. I’ve noticed, even though it will implicitely define self, the variable display on the preview is actually an underscore for some reason. Also, the type is not explicitely defined and inferred as unknown, so the type solver doesn’t realise it’s a colon function, therefore not displaying autocomplete for it.
I’ve has some success, but also some failures, with explicitely defining it this way, but it only works for OOP:
type Object = {
--attributes of objects
} & typeof(setmetatable({}, Class))
Which is weird, because it shouldn’t work for the same reasons autocomplete doesn’t show.