Connecting intellisense to an automatically defined self

Original Post (Answer below)

Say for example you had a simple class module, and in that module, you have a method (where self is automatically passed). Is there a way you can tell the intellisense (and thusly other editors of the script) that the passed self should be of said class?

I don’t believe this problem is mentioned on the official luau page for type annoations, the method in this post (distantly related) did not cause the intellisense to pick up on it, and this bug report was never updated with a confirmed fix.

Pictured: Intellisense not picking up that self should be of type class
image

copy n paste code
local class = {}
class.__index = class
class.ExampleVariable = "Howdy"

function class.new()
	return setmetatable({},class)
end

function class:print()
	print(self.)
end

return class

For anybody seeing this in the future:

This post is similar.

Code updated to feature solution
local class = {}
class.__index = class
class.ExampleVariable = "Howdy"

function class.new()
	return setmetatable({},class)
end

function class.print(self:ExportedType) -- This line was changed
	print(self.)
end

export type ExportedType = typeof(class) -- This line was added
return class

You could do something like:

type class = typeof(class.new())

then type assert self to be of type class (self = self :: class)

Another option if you don’t like the type assert method, would be to create a type for your methods and a type for your object’s interface like so:

type methods = {
	new: () -> (class);
	print: (self: class) -> ();
	ExampleVariable: 'Howdy';
	__index: methods;
}

type classInterface = {
	prop: true
}

type class = typeof(setmetatable({} :: classInterface, {} :: methods))

local class = {} :: methods
class.__index = class
class.ExampleVariable = "Howdy"

function class.new()
	return setmetatable({},class)
end

function class:print()
	
end

return class

image
image
image

1 Like

Do you know how the first method you provided plays into compiling/if its effect on performance is notable?

First one I would assume would play into compiling, yes. But the performance impact would be extremely minute.

If you want one that doesn’t have an assignment like that, you could do something like

function class.print(self: class)

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