For example, say I have an instance of Part named “Button” in Workspace. Button has one child, an instance of ClickDetector named “ClickDetector”.
local Button = game:GetService("Workspace").Button
local ClickDetector = Button.ClickDetector
Now, when you type the above in Roblox Studio, Roblox Studio gives you hints. For example, when defining ClickDetector, I type “Button” and Roblox gives me some options, one of them being the child ClickDetector.
However, let’s say I do this:
local Button: Part = game:GetService("Workspace").Button
Now, if I were to do local ClickDetector = Button., I wouldn’t get the ClickDetector child as a suggestion.
Instead, I only get the inferred properties of the class Part. It seems like Studio doesn’t bother checking the actual instance in game.Workspace, and instead uses a pre-written reference to tell you the class’s attributes, events, methods, etc.
Why is this? Is there a way to change this behavior while still using type annotations?
Types are separate from the hierarchy. You cannot explicitly set the type and preserve the hierarchy, as the context for the Instance (which is hidden in the type when you refer to it) is lost.
Why are you using annotations here? It should automatically infer the type as being ClickDetector (+ it’s Parent context) if the Instance exists already as you write the code (or maybe you need to enable --!strict for it to do that).
Also why are you using :GetService("Workspace")? Just use workspace.
You can just refer to typeof instance you are attempting to type
local Button: typeof(workspace.Part) = workspace.Button
This lets you access children and properties of the given object while having proper typechecking with said object’s types.
Which is accessing Button.ClickDetector with autocomplete in your case.
Just tell the typechecker what exactly you want to do. typeof helps you set an object as a template and/or inherit types from another object.
Follow the method above me. The reason why you’re type check doesn’t show children is because you’re only declaring that the instance is a part, and that only allows you to see its properties.
Like the person above me said, typeof sets the object as a template.