How to typecheck nested tables?

I’m wondering how I can add typings to a nested table, but I’ve looked on the forums and found nothing to my problem. Only solutions to local variables and or functions.

I have the following Lua and I want to typecheck Attachment so that Attach shows up whenever doing ...Attachment:Attach

return {

    Attachment = {

        Attach = function(self, Model: Model, Callback: (Animator: Animator, Animation: Animation) -> (Animator, Animation))
            ...
        end
    }
};
  1. Explicitly declared:
export type class = {
    someFunction: (self: MyClass, arg: string) -> (),
    nestedTable: {
        nestedFunction: (self: typeof(({} :: MyClass).nestedTable, arg: number) -> ()
    }
}
  1. Inferred:
--!strict

local class = {
	Attachment = {}
}

function class.Attachment.Attach(self: typeof(class.Attachment), model: Model): () -- etc.
	
end

-- syntactic sugar for above, however, loses self intellisense
function class.Attachment:Attach(model: Model): () -- etc.
	
end

You unfortunately cannot do the second method all in one table as the table isn’t “resolved” yet.

What’s the difference between explicitly and inferred?

You can nest the typechecking itself:

type callback = (Animator: Animator, Animation: Animation) -> (Animator, Animation)
type f = (self: any, Model: Model, Callback: callback) -> any
type response = {Attachment: {Attach: f}}

That seems like it would be a bit messy as well as a redundant part that could just be put in the arguments and such

Depends on what you are doing. You are better off doing the second method where the script analysis will return the type of your structured table.

I personally use method 1 for all my classes since I can essentially map out what I want my class to have before coding the functionality, and fine-tune the types without having to resort to this pattern:

image

Edit: Method 1 is also a great way of “hiding” certain keys from showing up, like internal variables.

Alright, I will try the first method and see if I can figure it out

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