Typechecking for an Index in a Table

so i’ve tried looking around for a bit and i found nothing, but this is essentially what i’m trying to achieve:

suppose you have this in a modulescript

function module:DefineThisWeirdThing()
    self.Thingy = workspace:WaitForChild("ThisRemoteFunction")
end

:DefineThisWeirdThing() essentially defines, in the module, self.Thingy is equal to ThisRemoteFunction in the workspace

let’s just say we can’t use :FindFirstChildOfClass() for this, how exactly would i make it so the typechecking treats it like a RemoteFunction?

i know that what i am essentially asking for is make an index in a table have this typechecking, which might not even be possible but i am just wondering if this is possible at all. no results really came up on google

thank u if u have a solution for this btw

nvm what the bart i found this

google search works

p.s now im sad that we cant do typechecking for this (still most likely impossible with how the typechecking works in lua)

You can actually do this with luau typechecking.

self.Thingy = workspace:WaitForChild("ThisRemoteFunction") :: RemoteFunction

The double-colon indicates to luau that WaitForChild should return the specified type you declared. In this context, we’re declaring it should be a RemoteFunction

If you plan on making code that is modular for anything that happens in the future, it’s useful to trust luau in most cases when you’re trying to get an instance. Typechecking will still work if we do this:

local FunctionInstance = workspace:WaitForChild("ThisRemoteFunction")
if not FunctionInstance:IsA("RemoteFunction") then
    warn(tostring(FunctionInstance) .. " was not a RemoteFunction.")
    return
end

-- luau's typechecker knows for sure that FunctionInstance is a RemoteFunction now because of the context it understands
self.Thingy = FunctionInstance

If you’d like to declare a table type instead, you can do this:

self = {
    Thingy = nil :: RemoteFunction?
}

-- Alternatively, you can make your own types
type YourTypeName = {
    Thingy : RemoteFunction?
}

If you want to learn more about types and creating your own custom types, you can check out Luau’s Type Checking reference.

wow ok so this is strange, that’s actually really nice so thank you, never knew that

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.